您的位置:首页 > 编程语言 > Java开发

Recover Binary Search Tree (Java)

2015-01-29 20:56 218 查看
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?

这道题的意思是需要将BST树中两个因错误交换的结点的值纠正过来。只需要交换值即可。

中序遍历,如果是正确的BST结果应该是非降序的,用pre和当前值比较,整个数列中有两次pre > 当前值root的情况(错误发生点)。 前一次取pre,后一次取root,交换这两个值即可。

Source

/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
TreeNode pre;
TreeNode a, b;
public void recoverTree(TreeNode root) {
if(root == null) return;
pre = null;
a = null;
b = null;
inorder(root);
if(a != null && b != null){
int temp = a.val;
a.val = b.val;
b.val = temp;
}
}
public void inorder(TreeNode root){
if(root == null) return;
inorder(root.left);
if(pre == null){
pre = root; //如果pre置为root.left,而left又是null时是无法取pre.val的
}
else{
if(pre.val > root.val){
if(a == null){
a = pre;
}
b = root; //a是序列中第一个出现降序的开始,b是a后面第一个降序的结尾 即序列中只有两次pre > root 一次取pre 一次取root即可
}
pre = root;
}
inorder(root.right);
}
}

Test

public static void main(String[] args){
TreeNode a = new TreeNode(2);
a.left = new TreeNode(3);
a.right = new TreeNode(1);
new Solution().recoverTree(a);
System.out.println(a.left.val);
System.out.println(a.right.val);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  LeetCode