Recover Binary Search Tree
2014-01-30 06:47
232 查看
Recover Binary Search Tree
Total Accepted: 4188 TotalSubmissions: 19186My Submissions
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.
这题关键在于inorder traversal. 首先需要3个全局指针pre,first,second。 pre始终指向traversal当前node的前一个,first是第一个错误的点,second是第二个错误的点。
注意点:两个错误点可能是相邻的,也可能是不相邻的。当第一次发现错误点的时候, first = pre, second = root, 把两个错误点都设了,防止之后没有错误点了,那么就是这两个了。
如果之后还有错误点,只更新 second 即可。
static TreeNode pre = null, first = null, second = null;
public static void recoverTree(TreeNode root) {
recoverTreeHelper(root);
if (first != null && second != null) {
int temp = first.val;
first.val = second.val;
second.val = temp;
}
}
public static void recoverTreeHelper(TreeNode root) {
if (root == null) return;
recoverTreeHelper(root.left);
if (pre == null) pre = root;
else if (root.val < pre.val) {
if (first == null) {
first = pre;
}
second = root;
}
pre = root;
recoverTreeHelper(root.right);
}
相关文章推荐
- LeetCode 099 Recover Binary Search Tree
- LeetCode-Recover Binary Search Tree-恢复二叉排序树
- Recover Binary Search Tree
- [leetcode-99]Recover Binary Search Tree(java)
- 99. Recover Binary Search Tree
- leetcode--Recover Binary Search Tree*
- Recover Binary Search Tree
- Recover Binary Search Tree--leetcode难题讲解
- leetcode--Recover Binary Search Tree
- Recover Binary Search Tree BST找乱序的两个元素 @LeetCode
- 好!recover-binary-search-tree(难)& 两种好的空间O(n)解法 & 空间O(1)解法
- 【Leetcode】Recover Binary Search Tree
- Leetcode--Recover Binary Search Tree
- [Leetcode] Recover Binary Search Tree
- LeetCode Recover Binary Search Tree
- Recover Binary Search Tree
- LeetCode Recover Binary Search Tree
- Recover Binary Search Tree
- [LeetCode] - Recover Binary Search Tree
- leetcode--Recover Binary Search Tree