99. 恢复二叉搜索树
二叉搜索树中的两个节点被错误地交换。
请在不改变其结构的情况下,恢复这棵树。
进阶:
- 使用 O(n) 空间复杂度的解法很容易实现。
- 你能想出一个只使用常数空间的解决方案吗?
实现代码
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<int> v;
int cnt = 0;
// 中序遍历找序列
void LDR(TreeNode* root) {
if (root == nullptr) return;
LDR(root->left);
v.push_back(root->val);
LDR(root->right);
}
void chm(TreeNode* root, int x, int y, int num) {
if (root) {
if (root->val == x || root->val == y) {
root->val ^= num;
if (++cnt == 2) return;
}
chm(root->left, x, y, num);
chm(root->right, x, y, num);
}
}
void recoverTree(TreeNode* root) {
LDR(root);
int l = -1, r = -1;
for (int i = 1; i < v.size(); i++) {
if (v[i - 1] > v[i]) {
if (l == -1) l = v[i - 1], r = v[i];
else {
r = v[i];
break;
}
}
}
// 改val
chm(root, l, r, l ^ r);
}
};