-
Notifications
You must be signed in to change notification settings - Fork 21
/
Recover Binary Search Tree.java
executable file
·97 lines (74 loc) · 1.91 KB
/
Recover Binary Search Tree.java
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
H
1529560210
tags: Tree, DFS, BST
BST里面有2个node misplace, 要归为. 要求: O(1) extra space
#### Observation
- BST inorder traversal should give small -> large sequence
- misplaced means: a **large**->small item would occur, and later a large>**small** would occur.
- The first large && second small item are the 2 candidates. Example
- [1, 5, 7, 10, 12, 15, 18]
- [1, 5, `15, 10`, `12, 7`, 18]
#### dfs, O(1) extra space
- traverse, and take note of the candidate
- at the end, swap value of the 2 candidates
#### O(n) space
- inorder traversal the nodes and save in array, find the 2 items misplanced and swap them
- But O(n) space should not be allowed
```
/*
Two elements of a binary search tree (BST) are swapped by mistake.
Recover the tree without changing its structure.
Example 1:
Input: [1,3,null,null,2]
1
/
3
\
2
Output: [3,1,null,null,2]
3
/
1
\
2
Example 2:
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?
*/
// DFS, track nodeA, nodeB. Beats 100%: https://leetcode.com/submissions/detail/159980654/
class Solution {
TreeNode nodeA, nodeB, preNode = new TreeNode(Integer.MIN_VALUE);
public void recoverTree(TreeNode root) {
dfs(root);
// swap
int temp = nodeA.val;
nodeA.val = nodeB.val;
nodeB.val = temp;
}
/*
DFS function that in-order traverse the tree.
*/
private void dfs(TreeNode node) {
if (node == null) return;
dfs(node.left);
// Assign nodeA, nodeB
if (nodeA == null && preNode.val >= node.val) nodeA = preNode;
if (nodeA != null && preNode.val >= node.val) nodeB = node;
preNode = node; // regardless, assign preNode as curr mid
dfs(node.right);
}
}
```