题目:
给你二叉搜索树的根节点 root ,该树中的 恰好 两个节点的值被错误地交换。请在不改变其结构的情况下,恢复这棵树 。
示例:
输入:root = [3,1,4,null,null,2]
输出:[2,1,4,null,null,3]
解释:2 不能在 3 的右子树中,因为 2 < 3 。交换 2 和 3 使二叉搜索树有效。
需要使用到的知识点:
1, 中序遍历搜索二叉树得到的元素向量为递增向量。
2,在含有交换位置的递增向量中找到相应的被交换的元素。
3,按照节点val恢复被交换节点的搜索树。
4,最基础最终要的,当然是会中序遍历二叉树啦,哈哈哈哈哈。
code c++ edition:
class Solution {
public:
void inorder(TreeNode* root, vector & re){
if (root == nullptr)
return;
inorder(root->left, re);
re.push_back(root->val);
inorder(root->right, re);
}
pair find_swap(vector& res){
int index1 = -1, index2 = -1;
int n = res.size();
for (int i = 0;i< n-1;++i){
if (res[i+1]val == x || r->val == y) {
r->val = r->val == x ? y : x;
if (--count == 0) {
return;
}
}
recover(r->left, count, x, y);
recover(r->right, count, x, y);
}
}
void recoverTree(TreeNode* root) {
//中序遍历二叉搜索树,遍历结果返回为vector
vector inorder_result;
inorder(root, inorder_result);
//找到交换顺序的节点,以中序遍历结果向量的索引返回
pair swap_val = find_swap(inorder_result);
//将乱序的节点进行交换
int count =2;
recover(root, count, swap_val.first, swap_val.second);
}
};



