-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRecover Binary Search Tree.txt
43 lines (43 loc) · 1.17 KB
/
Recover Binary Search Tree.txt
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
41
42
43
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
void recoverTree(TreeNode *root) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
TreeNode *prev = NULL, *succ = NULL;
TreeNode *l = findFirst(root, prev), *r = findLast(root, succ);
int t = l->val;
l->val = r->val;
r->val = t;
}
TreeNode* findFirst(TreeNode* root, TreeNode*& prev) {
if (!root)
return NULL;
TreeNode* l = findFirst(root->left, prev);
if (l)
return l;
if (prev && (prev->val > root->val))
return prev;
prev = root;
return findFirst(root->right, prev);
}
TreeNode* findLast(TreeNode* root, TreeNode*& succ) {
if (!root)
return NULL;
TreeNode* r = findLast(root->right, succ);
if (r)
return r;
if (succ && (root->val > succ->val))
return succ;
succ = root;
return findLast(root->left, succ);
}
};