您的位置:首页 > 其它

LeetCode刷题笔录Recover Binary Search Tree

2014-08-20 00:08 344 查看
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的问题,第一反应就应该是inorder traversal.利用O(n)的空间复杂度的话比较简单,用一个数组存储inorder traversal的所有结果,排个序,再赋值回去就好了。这个方法对于有任意N个元素位置不对的BST也可行。

这里只有两个node位置错了,因此可以只要找到这两个节点,用O(lgn)空间复杂度的递归就可以找到。维护三个指针,pre, first和second。pre用来存储inorder traversal的前一个节点,用以和当前节点进行比较来决定当前节点是否违反bst的性质。first和second存储两个放错了的node。

比如这个正确的BST:

1 2 3 4 5 6 7

交换一下1和4得到:

4 2 3 1 5 6 7

遍历时,pre=4,root=2时会发生第一次Inconsistency,这时让first=pre,即first=4.

第二次pre=3,root=1时会发生第二次inconsistency,这时让second=root,即second=1.

这样就找到了两个节点,交换他们的值就行了。

/**
* Definition for binary tree
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
public class Solution {
TreeNode pre;
TreeNode first;
TreeNode second;

public void recoverTree(TreeNode root) {
pre = null;
first = null;
second = null;
inorder(root);
int temp = first.val;
first.val = second.val;
second.val = temp;
}

public void inorder(TreeNode root){
if(root == null)
return;
inorder(root.left);

if(pre == null){
pre = root;
}
else{
//a violation of BST
if(pre.val > root.val){
if(first == null)
first = pre;
second = root;
}
pre = root;
}

inorder(root.right);
}
}
如果要O(1)的空间复杂度的话,需要用到Threaded binary tree,可以不需要额外的stack来遍历二叉树。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: