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?
这题想了比较久=.=
第一感觉是用map<TreeNode*,int>
存下中序遍历的结果。再交换错误的两个。但是不太符合题意。
比如说一个BST用中序遍历的结果是:
1,2,3,4,5,6,7
其中有两个搞混了(2和4搞混了):
1,4,3,2,5,6,7
当检查到3时就会发现出现了错误(应该是严格单调增的),将3和他前面的4记录下来:{4,3}
在当检查到2时又出现了错误,第二次发现错误将结果改为{4,2}
至多出现两次错误,所以答案就是{4,2}
但是也有可能是相邻两个数混了(5和6混了):
1,2,3,4,6,5,7
这样只会出现一次错误,结果就是{6,5}
所以还需要记录在某个节点之前的节点before
/**
* 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 *a = NULL;
TreeNode *b = NULL;
TreeNode *before = NULL;
void find(TreeNode *root){
if(root == NULL) return;
if(root->left!=NULL) find(root->left);
if(before!=NULL&&root->val<before->val) {
if(a==NULL){
a = before;
b = root;
}
else{
b = root;
}
}
before = root;
if(root->right!=NULL) find(root->right);
}
void recoverTree(TreeNode *root) {
//if(root == NULL) return;
int tem;
find(root);
if(a!=NULL){
tem = b->val;
b->val = a->val;
a->val = tem;
}
}
};