Problem description:

Two elements of a binary search tree (BST) are swapped by mistake.

Recover the tree without changing its structure.

Example 1:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Input: [1,3,null,null,2]

1
/
3
\
2

Output: [3,1,null,null,2]

3
/
1
\
2

Example 2:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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?

Solution:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
/**
* 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:
TreeNode *first, *second; //store the position that needs to be swap
TreeNode *prev; // store the previous position in tree
void recoverTree(TreeNode* root) {
first = second = prev = NULL;
//inorder traversal
dfs(root);
if (first != NULL && second != NULL) {
int tmp = first -> val;
first -> val = second -> val;
second -> val = tmp;
}
}
void dfs(TreeNode* root) {
// check left first
if (root -> left != NULL) dfs(root -> left);

// if there's any disorder, store the position.
if (prev != NULL && prev -> val > root -> val) {
if (first == NULL)
first = prev;
if (first != NULL)
second = root;
}
// current root become prev
prev = root;
// right subtree
if (root -> right != NULL) dfs(root -> right);
}
};

time complexity: $O(n)$
space complexity: $O(logn)$

Solution2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/**
* 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:
TreeNode *first= NULL, *second= NULL;
TreeNode *prev= new TreeNode(INT_MIN);
void recoverTree(TreeNode* root) {
inorder(root);
swap(first->val, second->val);
}

void inorder(TreeNode* root){
if(!root) return;
inorder(root->left);

//do something
if(first == NULL && prev->val >= root->val) first= prev;
if(first != NULL && prev->val >= root->val) second= root;
//end do something
prev= root;
inorder(root->right);
}
};

reference:
https://goo.gl/35YynW
https://goo.gl/SVX1A6