Two elements of a binary search tree (BST) are swapped by mistake.
Recover the tree without changing its structure.
这里我就写了一个递归地遍历的方法,想找到6,我们需要的是找到第一个数,如果他比他前面的数要小,那么前一个数就是我们要找的6。 找到第一个数之后,接着再找,如果我们还能找到一个数,比他的前面的数要小,那么这个数就是我们的3。 如果不能的话,那么第一次找到的“这个数”和“前一个数”就直接是我们的答案。
注意几点:
1. 我最开始以为指针传递进来了,就都是call by reference, 后来发现不是,如果想传入一个递归中可以随时修改的像int &x, 这样的指针的话,我们也需要在指针的面前加引用符号。
代码如下:
class Solution {
public:
void recoverTree(TreeNode* root) {
vector<TreeNode*> res;
TreeNode* pre = NULL;
help(root,pre,res);
int tmp = res[0]->val;
res[0]->val = res[1]->val;
res[1]->val = tmp;
return;
}
void help(TreeNode* root, TreeNode* &pre, vector<TreeNode*> &res) {
if (!root) return;
help(root->left,pre,res);
if (pre) {
if (root->val < pre->val) {
if (res.empty()) {
res.push_back(pre);
res.push_back(root);
} else {
res[1] = root;
}
}
}
pre = root;
help(root->right,pre,res);
}
};