您的位置:首页 > 其它

Leetcode: Recover Binary Search Tree

2015-01-28 04:10 453 查看
Problem:

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.

Solution:

Using Inorder Traverse.

Code

/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
TreeNode p;
TreeNode q;
TreeNode tmp = new TreeNode(Integer.MIN_VALUE);
public void recoverTree(TreeNode root) {
if (root == null) return;
recover(root);
if (p != null && q != null) {
int t = p.val;
p.val = q.val;
q.val = t;
}

}
public void recover(TreeNode root) {
if (root == null) return;
recover(root.left);
if (tmp != null && root.val < tmp.val) {
if(p == null) {
p = tmp;
q = root;
} else {
q = root;
}
}
tmp = root;
recover(root.right);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: