【LeetCode】Recover Binary Search Tree

参考链接

http://blog.csdn.net/worldwindjp/article/details/21694179
http://www.2cto.com/kf/201310/251524.html

http://blog.csdn.net/pickless/article/details/11880851

题目描述


题目分析

Recover Binary Search Tree

  Total Accepted: 8871  Total Submissions: 39192 My 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.

Have you been asked this question in an interview? 

总结

二叉排序树中有两个节点被交换了,要求把树恢复成二叉排序树。
最简单的办法,中序遍历二叉树生成序列,然后对序列中排序错误的进行调整。最后再进行一次赋值操作。
但这种方法要求n的空间复杂度,题目中要求空间复杂度为常数,所以需要换一种方法。
递归中序遍历二叉树,设置一个pre指针,记录当前节点中序遍历时的前节点,如果当前节点大于pre节点的值,说明需要调整次序。
有一个技巧是如果遍历整个序列过程中只出现了一次次序错误,说明就是这两个相邻节点需要被交换。如果出现了两次次序错误,那就需要交换这两个节点。

代码示例



/** 
 * Definition for binary tree 
 * struct TreeNode { 
 *     int val; 
 *     TreeNode *left; 
 *     TreeNode *right; 
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} 
 * }; 
 */ 
class Solution {  
public:  
    TreeNode *s1,*s2,*pre;  
    void hehe(TreeNode *root)  
    {  
        if(!root)return ;  
        hehe(root->left);  
        if(pre&& pre->val > root->val)  
        {  
            if(s1==NULL)s1=pre,s2=root;  
            else s2=root;  
        }  
        pre=root;  
        hehe(root->right);  
    }  
    void recoverTree(TreeNode *root) {  
        if(!root)return ;  
        s1=s2=pre=NULL;  
        hehe(root);  
        swap(s1->val,s2->val);  
    }  
};  
// http://blog.csdn.net/havenoidea  



推荐学习C++的资料

C++标准函数库
在线C++API查询
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值