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.
思路:pre-order traversal, 之前遍历过的元素永远小于之后遍历过的元素。依次遍历,找到乱序的两个后交换。根据如下遍历方法,从遍历的节点n1到root之间的所有节点都是顺序的,所以n1和root是乱序的两个
class Solution {
public:
void recoverTree(TreeNode *root) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
TreeNode *n1=NULL;
TreeNode *n2=NULL;
TreeNode *prev=NULL;
findTwoNodes(root,n1,n2,prev);
if(n1!=NULL && n2!=NULL)
{
int tmp=n2->val;
n2->val=n1->val;
n1->val=tmp;
}
}
void findTwoNodes(TreeNode *root, TreeNode *&n1, TreeNode *&n2, TreeNode *&prev)
{
if(root==NULL) return;
findTwoNodes(root->left,n1,n2,prev);
if(prev!=NULL && prev->val > root->val)
{
n2=root;
if(n1==NULL)
{
n1=prev;
}
}
prev=root;
findTwoNodes(root->right,n1,n2,prev);
}
};