Topic:
Elements of a binary search tree (BST) is swapped by mistake.
Recover the tree without changing its structure.
Note:
A solution using O (n) space is pretty straight forward. Could you devise a constant space solution?
test instructions and analysis: two point order of a binary search tree is wrong, restore it. to find two points of the sequential exchange, the exchange point is a couple of situations: (1) One is the adjacent two points exchange, so that only one reverse order (2) is not adjacent two points exchange, there are two reverse, the two points of the exchange is the first reverse of the first point and second order of the second point, find these two points, and then swap.
Code:
/*** Definition for a binary tree node. * public class TreeNode {* int val; * TreeNode left; * TreeNode rig Ht * TreeNode (int x) {val = x;} }*/classSolution {TreeNode Firstnode=NULL; TreeNode Secondnode=NULL; TreeNode prevelement=NewTreeNode (Integer.min_value); Public voidRecovertree (TreeNode root) {//two point order of a binary search tree is wrong, restore it//to find two points of the sequential exchange, the exchange point is a couple of situations: (1) One is the adjacent two points exchange, so that only one reverse order (2) is not adjacent two points exchange, there are two reverse, the two points of the exchange is the first reverse of the first point and second order of the second point, find these two points, Then swaptraverse (root); inttemp =Firstnode.val; Firstnode.val=Secondnode.val; Secondnode.val=temp; } Public voidTraverse (TreeNode node) {if(node = =NULL) return; Traverse (Node.left); if(Firstnode = =NULL&& prevelement.val >= node.val) {//ReverseFirstnode =prevelement; } if(firstnode!=NULL&& prevelement.val>=node.val) Secondnode=node; Prevelement=node; Traverse (node.right); }}
[Leetcode] 99. Recover Binary Search Tree Java