99. Recover Binary Search Tree
99. Recover Binary Search Tree https://leetcode.com/problems/recover-binary-search-tree/discuss/32535/No-Fancy-Algorithm-just-Simple-and-Powerful-In-Order-Traversal https://www.youtube.com/watch?v=LR3K5XAWV5k /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution{ TreeNode firstElement = null; TreeNode secondElement = null; // The reason for this initialization is to avoid null pointer exception in the first comparison when prevElement has not been initialized TreeNode prevElement = new TreeNode(Integer.MIN_VALUE); public void recoverTree(TreeNode root){ traverse(root); // after done traversing, swap the first node value and the second node value int tmp = firstElement.val; firstElement.val = secondElement.val; secondElement.val = tmp; } private void traverse(TreeNode root){ if(root == null) return; traverse(root.left); if(firstElement == null && prevElement.val >= root.val){ firstElement = prevElement; } if(firstElement != null && prevElement.val >= root.val){ secondElement = root; } prevElement = root; traverse(root.right); } } // two cases // one is if the original bst tree in order is 1 2 3 4 5 6 7 // after swap : we have 1 6 3 4 5 2 7 // 6 and 2 are swapped. // there are two abonormal looking pairs : which are 6 3 and 5 2 // anothe case is // the original bst in order is 1 2 3 4 5 6 7 // after swap : 1 3 2 4 5 6 7 // 3 and 2 are swapped // there is only one pair of abonormal looking pair which is 3 and 2 // combine above two cases, after we meet the first pair, we don't know // if there is only one pair, or there is another pair , so we store the root of the first pair as // the second element . just in case there is only one pair // if there is another pair later, we can just replace the second element with the root of the second pair
Two elements of a binary search tree (BST) are swapped by mistake.
Recover the tree without changing its structure.
Example 1:
Input: [1,3,null,null,2] 1 / 3 \ 2 Output: [3,1,null,null,2] 3 / 1 \ 2
Example 2:
Input: [3,1,4,null,null,2] 3 / \ 1 4 / 2 Output: [2,1,4,null,null,3] 2 / \ 1 4 / 3
Follow up:
- A solution using O(n) space is pretty straight forward.
- Could you devise a constant space solution?
posted on 2018-08-28 20:43 猪猪🐷 阅读(134) 评论(0) 收藏 举报
浙公网安备 33010602011771号