-
Notifications
You must be signed in to change notification settings - Fork 31
/
Copy path99. Recover Binary Search Tree.c
68 lines (52 loc) · 1.55 KB
/
99. Recover Binary Search Tree.c
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
/*
99. Recover Binary Search Tree
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?
*/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
void find_nodes(struct TreeNode *node,
struct TreeNode **n1,
struct TreeNode **n2,
struct TreeNode **n3,
struct TreeNode **p) {
if (!node || *n3) return; // all are found
find_nodes(node->left, n1, n2, n3, p);
if (*p && (*p)->val > node->val) { // found two nodes in wrong order
if (!*n1) {
*n1 = *p; // save first node
*n2 = node; // save second node
} else {
*n3 = node; // save third node
return; // all are found
}
}
*p = node;
find_nodes(node->right, n1, n2, n3, p);
}
void recoverTree(struct TreeNode* root) {
struct TreeNode *n1, *n2, *n3, *p;
int k;
n1 = n2 = n3 = p = NULL;
find_nodes(root, &n1, &n2, &n3, &p);
if (n1) {
if (!n3) n3 = n2;
k = n1->val; // swap first and third node
n1->val = n3->val;
n3->val = k;
}
}
/*
Difficulty:Hard
Total Accepted:75.7K
Total Submissions:253.9K
Related Topics Tree Depth-first Search
*/