LeetCode 99 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?
Concept; recursion. Use recursion to find the maximum node of the Left subtree, and use recursion to find the minimum node of the right subtree;
1 If the value of the maximum node of the Left subtree is greater than that of the smallest node of the right subtree, it indicates that the maximum node of the Left subtree is exchanged with the smallest node of the right subtree;
2 If the value of the maximum node of the Left subtree is greater than that of the root node, it indicates that the root node is exchanged with the maximum node of the Left subtree;
3 if the value of the maximum node of the right subtree is smaller than that of the root node, it indicates that the root node is exchanged with the minimum node of the right subtree;
4. If none of the above three conditions occur, it means that one or two nodes in the left subtree have been exchanged or one or two nodes in the right subtree have been exchanged, recursively check whether the left and right subtree have nodes;
public class Solution {private TreeNode findMin(TreeNode root) {TreeNode result, l = root, r = root;if (root.left != null)l = findMin(root.left);if (root.right!= null)r = findMin(root.right);result = l.val < r.val ? l : r;return result.val < root.val ? result : root;}private TreeNode findMax(TreeNode root) {TreeNode result, l = root, r = root;if (root.left != null)l = findMax(root.left);if (root.right != null)r = findMax(root.right);result = l.val > r.val ? l : r;return result.val > root.val ? result : root;}public void recoverTree(TreeNode root) {TreeNode l=root,r=root;if(root==null||(root.left==null&&root.right==null)) return;if(root.left!=null) l=findMax(root.left);if(root.right!=null) r=findMin(root.right);if(l.val>r.val){int temp=l.val;l.val=r.val;r.val=temp;return ;}else if(l.val>root.val){int temp=l.val;l.val=root.val;root.val=temp;return ;}else if(r.val