Two elements of a binary search tree (BST) are swapped by mistake.
Recover the tree without changing its structure.
Note:
A solution using O(n) space is pretty straight forward. Could you devise a constant space solution
1 /** 2 * Definition for binary tree 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 TreeNode* pre = nullptr; 13 TreeNode* mistake1 = nullptr; 14 TreeNode* mistake2 = nullptr; 15 void recoverTree(TreeNode *root) { 16 inorder(root); 17 if(mistake1 && mistake2) swap(mistake1->val,mistake2->val); 18 } 19 void inorder(TreeNode* root){ 20 if(root == nullptr) return ; 21 inorder(root->left); 22 if(pre == nullptr) pre = root; 23 else{ 24 if(pre->val > root->val){ 25 if(mistake1 == nullptr) mistake1=pre; 26 mistake2 = root; 27 } 28 pre = root; 29 } 30 inorder(root->right); 31 } 32 };