您的位置:首页 > 编程语言 > Go语言

Recover Binary Search Tree

2014-01-30 06:47 232 查看


Recover Binary Search Tree

 Total Accepted: 4188 Total
Submissions: 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);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  algorithm leetcode