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.
题意:二叉搜索树中存在两个值互换了位置,要求不改变树的结构的情况下,交换两个值。
一说到二叉搜索树,我们要很快联想到其中序遍历是排序的,所以可以根据是否排序来确定元素的位置是否正确。并且我
们可以轻易证明,要是有两处后者小于前者,那么第一次的前者应该和第二次的后者交换,我们标记节点为s1,s2.
要是只有一处后者小于前者,那么前者为s1,后者为s2,这里遍历采用递归的方式。
最后交换s1和s2的值即可。
class Solution {
public:
TreeNode *s1,*s2,*pre;
void recoverTree(TreeNode *root) {
s1=s2=pre=NULL;
inorder(root);
swap(s1->val,s2->val);
return;
}
void inorder(TreeNode *root)
{
if(!root)
return;
inorder(root->left);
if(pre&&pre->val>root->val)
{
if(s1==NULL)
s1=pre,s2=root;
else
s2=root;
}
pre=root;
inorder(root->right);
}
};