版权声明:本文为博主原创文章,未经博主许可允许转载。 https://blog.csdn.net/qq_29600137/article/details/89300714
Two elements of a binary search tree (BST) are swapped by mistake.
Recover the tree without changing its structure.
Example 1:
Input: [1,3,null,null,2] 1 / 3 \ 2 Output: [3,1,null,null,2] 3 / 1 \ 2
Example 2:
Input: [3,1,4,null,null,2] 3 / \ 1 4 / 2 Output: [2,1,4,null,null,3] 2 / \ 1 4 / 3
Follow up:
- A solution using O(n) space is pretty straight forward.
- Could you devise a constant space solution?
题目大意:
二叉树中有两个错误位置,交换这两个位置。
解题思路:
中序遍历之后,sort排序可以得到正确的二叉树。此时再次中序遍历,找到位置不对应的两个位置返回,交换中间值。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
private:
vector<int> ans;
int idx ;
void search(TreeNode* tmp){
if(tmp->left==NULL&&tmp->right==NULL){
ans.push_back(tmp->val);
return;
}
if(tmp->left!=NULL)
search(tmp->left);
ans.push_back(tmp->val);
if(tmp->right!=NULL)
search(tmp->right);
}
void search_to(TreeNode *tmp, TreeNode *&node1, TreeNode *&node2){
if(tmp->left==NULL&&tmp->right==NULL){
if(tmp->val != ans[idx]){
if(node1 == NULL){
node1 = tmp;
}else{
node2 = tmp;
}
}
idx++;
return;
}
if(tmp->left!=NULL)
search_to(tmp->left, node1, node2);
if(tmp->val != ans[idx]){
if(node1 == NULL){
node1 = tmp;
}else{
node2 = tmp;
}
}
idx++;
if(tmp->right!=NULL)
search_to(tmp->right, node1, node2);
}
public:
void recoverTree(TreeNode* root) {
// 中序遍历->vector
// 排序
// vector->中序替换
search(root);
int len = ans.size();
sort(ans.begin(), ans.end());
idx = 0;
TreeNode *node1=NULL, *node2=NULL;
search_to(root, node1, node2);
int val = node1->val;
node1->val = node2->val;
node2->val = val;
}
};