Recover Binary Search Tree
Two elements of a binary search tree (BST) are swapped by mistake.
Recover the tree without changing its structure.
Note:
A solution using O (N) Space is pretty straight forward. cocould you devise a constant space solution?
Algorithm ideas:
Train of Thought 1: Find the Middle-order traversal sequence, space complexity O (N), tip requires that only the O (1) space can be opened.
Code omitted
Train of Thought 2: In the middle order traversal, every vertex is recorded as its precursor, record the previous node pre of the current pointer cur, if pre. val is greater than cur. val indicates the wrong order. In most cases, there are two wrong orders. If there is one wrong order, it means that adjacent nodes need to be exchanged.
1 public class Solution { 2 TreeNode first = null,second = null,pre = null; 3 public void recoverTree(TreeNode root) { 4 findNode(root); 5 swap(first, second); 6 } 7 private void findNode(TreeNode root){ 8 if(root == null){ 9 return;10 }11 if(root.left != null ) findNode(root.left);12 if(pre != null && root.val < pre.val){13 if(first == null){14 first = pre;15 }16 second = root;17 }18 pre = root;19 if(root.right != null) findNode(root.right);20 }21 private void swap(TreeNode node1,TreeNode node2){22 int tem = node1.val;23 node1.val = node2.val;24 node2.val = tem;25 }26 }