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
/** * 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 help(TreeNode *root,TreeNode *&pre,vector<TreeNode*> &ret) { if(root==NULL) { return; } help(root->left,pre,ret); if(pre!=NULL&&pre->val>root->val) { ret.push_back(pre); ret.push_back(root); } pre=root; help(root->right,pre,ret); } void recoverTree(TreeNode* root) { vector<TreeNode*> ret; TreeNode *pre=NULL; help(root,pre,ret); if(ret.size()>0) { if(ret.size()==2) { swap(ret[0]->val,ret[1]->val); } else if(ret.size()==3) { swap(ret[0]->val,ret[2]->val); } else { swap(ret[0]->val,ret[3]->val); } } } };