Recover Binary Search Tree
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.
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
TreeNode *p,*q;
public:
void dfs(TreeNode *cur,TreeNode * &pre){
if(cur==NULL)return;
dfs(cur->left,pre);
if(pre!=NULL&&pre->val>cur->val){
if(p==NULL) p=pre;
q=cur;
}
pre=cur;
dfs(cur->right,pre);
}
void recoverTree(TreeNode *root) {
p=q=NULL;
TreeNode *pre=NULL;
dfs(root,pre);
swap(p->val,q->val);
}
};