285. Inorder Successor in BST

Given a binary search tree and a node in it, find the in-order successor of that node in the BST.

Note: If the given node has no in-order successor in the tree, return null.

解法1: O(N) Space

最直观的方法,就是先做一遍in order, 存起来,然后找出来目标node前一个node即可。
C++

1

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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
List<TreeNode> list = new ArrayList<TreeNode>();
if (root == null || p == null) {
return null;
}
helper(root, list);
for (int i = 0; i < list.size(); i++) {
if (list.get(i) == p) {
if (i == list.size() - 1) {
return null;
} else {
return list.get(i + 1);
}
}
}
return null;
}
private void helper(TreeNode root, List<TreeNode> list) {
if (root == null) {
return;
}
helper(root.left, list);
list.add(root);
helper(root.right, list);
}
}

解法2: O(1) Space

lang: 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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
TreeNode prev = null;
TreeNode res = null;
public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
if (root == null || p == null) {
return null;
}
helper(root, p);
return res;
}
private void helper(TreeNode root, TreeNode p) {
if (root == null) {
return;
}
helper(root.left, p);
if (prev == p) {
res = root;
prev = root;
return;
}
prev = root;
helper(root.right, p);
}
}

解法3: Iterative

lang: 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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
if (root == null) return root;
Stack<TreeNode> stack = new Stack<>();
TreeNode prev = null;
while (!stack.isEmpty() || root != null) {
if (root != null) {
stack.push(root);
root = root.left;
} else {
root = stack.pop();
if (prev == p) return root;
prev = root;
root = root.right;
}
}
return null;
}
}