99. Recover Binary Search Tree
Hard
99658FavoriteShare
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?
Accepted
132,582
Submissions
366,722
/**
* 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 {
public:
void recoverTree(TreeNode* root) {
vector<int> in;
vector<TreeNode*> intrees;
intra(root,in,intrees);
sort(in.begin(),in.end());
for(int i=0;i<in.size();i++){
intrees[i]->val=in[i];//直接对指针所指对象进行修改
}
}
void intra(TreeNode* root,vector<int>& in,vector<TreeNode*>& intrees){
if(root==NULL) return;
intra(root->left,in,intrees);
in.push_back(root->val);
intrees.push_back(root);
intra(root->right,in,intrees);
}
};