您的位置:首页 > 其它

Leetcode Recover Binary Tree

2015-10-17 21:13 302 查看
*

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.

*

public class Solution {
TreeNode pre;
TreeNode first;
TreeNode second;
public void recoverTree(TreeNode root) {
pre=null;first=null;second=null;
inorder(root);

if (first!=null){
if (second==null)second=pre;
int tmp= first.val;
first.val=second.val;
second.val=tmp;
}

}
public    void inorder (TreeNode root){
if (root==null)
return;
if (root.left!=null)
inorder(root.left);
if (pre!=null){
if (first==null && pre.val>root.val)
first=pre;
else if(first!=null && root.val>first.val )
second=pre;

if (first!=null && second!=null)
return;
}
pre=root;
if (root.right!=null)
inorder(root.right);
}
}


代码基本大同小异,上次 通过是1年5个月前的事,前两天笔试出了这个题又不会做了,拿出来复习一下。

1。首先碰见搜索二叉树肯定是中序遍历,中序遍历后是个有序有序,所以可以找出哪些节点有冲突。

在找的时候,需要加一个pre指针。 这个用法还挺实用的,把一颗二叉树转换成循环链表 也要加上这个pre指针。

2。就是找到冲突节点时候怎么处理。

假设只有两个冲突节点,如A1,A2 那这两个就是我们所要求的值 。直接替换即可。

如果找到四个冲突节点。 A1 A2 B1 B2 满足 A1>A2 B1>B2 这四个节点中有两个节点的位置是冲突的是哪两个节点呢。

当时笔试就卡在这个地方了。 被破坏的两个节点肯定是A中一个,B中一个,假设A2是破坏的节点,那么A2要和B 中的节点交换,但是仍然小于A1,所以A2不是被破坏的节点,A1才是。 同理,B1如果是被破坏的节点,B1换到前面去 仍然比B2大,所以B2才是破坏的节点。。

所以判定 当有Pre 节点是 和pre节点比较值得大小,如果有冲突,看是第一对冲突节点和第二对冲突节点。只找到一对冲突节点,那就返回这一对,所以有

if(pre!=null && pre.val>root.val){
if(first==null){
//找到第一队冲突节点
first=pre;
second=root;
}else{
//直接确认第二个冲突节点是第二对的第二个。
second=root;
}


所以所以前写的代码还是有点问题的,当时不知道怎么过的。。。。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: