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. Could you devise a constant space solution?
Solution
If we traverse the tree inorder, we just need to identify the 2 elements that are misplaced and swap their values. We also keep a third pointer that points to the previous element as it is needed to identify when an element is misplaced./** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { TreeNode pre, node1, node2; public void recoverTree(TreeNode root) { pre =null; node1 = null; node2 = null; inOrder(root); int temp = node1.val; node1.val = node2.val; node2.val = temp; } private void inOrder(TreeNode root) { if (root == null) return; inOrder(root.left); if(pre == null) pre = root; else if(node1 == null && pre.val > root.val) { node1 = pre; node2 = root; } else if(pre.val > root.val) { node2 = root; } pre = root; inOrder(root.right); } }
No comments :
Post a Comment