参考链接
http://blog.csdn.net/worldwindjp/article/details/21694179
http://www.2cto.com/kf/201310/251524.html
http://blog.csdn.net/pickless/article/details/11880851
题目描述
题目分析
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.
总结
二叉排序树中有两个节点被交换了,要求把树恢复成二叉排序树。最简单的办法,中序遍历二叉树生成序列,然后对序列中排序错误的进行调整。最后再进行一次赋值操作。
但这种方法要求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
/**
* 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查询