Recover Binary Search Tree
2015-01-26 19:30
369 查看
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. Could you devise a constant space solution?
confused what
"{1,#,2,3}"means? >
read more on how binary tree is serialized on OJ.
Java代码:
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public 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) { // In order traversal to find the two elements traverse(root); // Swap the values of the two nodes int temp = firstElement.val; firstElement.val = secondElement.val; secondElement.val = temp; } private void traverse(TreeNode root) { if (root == null) return; traverse(root.left); // Start of "do some business", // If first element has not been found, assign it to prevElement (refer to 6 in the example above) if (firstElement == null && prevElement.val >= root.val) { firstElement = prevElement; } // If first element is found, assign the second element to the root (refer to 2 in the example above) if (firstElement != null && prevElement.val >= root.val) { secondElement = root; } prevElement = root; // End of "do some business" traverse(root.right); } }
相关文章推荐
- [leedcode 99] Recover Binary Search Tree
- [leetcode] Recover Binary Search Tree
- leetcode 之 Recover Binary Search Tree
- Recover Binary Search Tree
- leetcode Recover Binary Search Tree
- leetcode_c++:树: Recover Binary Search Tree(099)
- leetcode -- Recover Binary Search Tree -- 重点
- LeetCode – Refresh – Recover Binary Search Tree
- Leetcode234: Recover Binary Search Tree
- 99. Recover Binary Search Tree(难)
- 99. Recover Binary Search Tree
- [Leetcode] Recover Binary Search Tree
- leetcode Recover Binary Search Tree
- [LeetCode]Recover Binary Search Tree
- Leetcode 99 Recover Binary Search Tree
- 【Recover Binary Search Tree】cpp
- LeetCode OJ - Recover Binary Search Tree
- 【LeetCode】Recover Binary Search Tree
- 【LeetCode OJ】Recover Binary Search Tree
- LeetCode 99: Recover Binary Search Tree