-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRecover_Binary_Search_Tree.cpp
More file actions
38 lines (36 loc) · 1.24 KB
/
Recover_Binary_Search_Tree.cpp
File metadata and controls
38 lines (36 loc) · 1.24 KB
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
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
/*
anson's solution.
inorder travel, the first node was initialized once and all.
the second node was the last bad node, compared with the first node.
that's all....
*/
//O(N)
class Solution {
public:
void recoverTree(TreeNode *root) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
TreeNode *prev = NULL, *first = NULL, *second = NULL;
recoverTreeHelper(root, prev, first, second);
swap(first->val, second->val);
}
void recoverTreeHelper(TreeNode *curNode, TreeNode *&preNode, TreeNode *&first, TreeNode *&second) {
if (curNode == NULL) return;
recoverTreeHelper(curNode->left, preNode, first, second);
if (preNode && preNode->val > curNode->val) {
if (first == NULL) first = preNode;
second = curNode;
}
preNode = curNode;
recoverTreeHelper(curNode->right, preNode, first, second);
}
};