-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathInorderSuccessorInBST.java
More file actions
49 lines (41 loc) · 1.15 KB
/
InorderSuccessorInBST.java
File metadata and controls
49 lines (41 loc) · 1.15 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
39
40
41
42
43
44
45
46
47
48
49
package binary_search_tree;
/**
* Description: https://leetcode.com/problems/inorder-successor-in-bst
* Difficulty: Medium
*/
public class InorderSuccessorInBST {
/**
* Time complexity: O(h)
* Space complexity: O(1)
*/
public TreeNode inorderSuccessorViaIteration(TreeNode root, TreeNode p) {
TreeNode successor = null;
while (root != null) {
if (p.val >= root.val) {
root = root.right;
} else {
successor = root;
root = root.left;
}
}
return successor;
}
/**
* Time complexity: O(h)
* Space complexity: O(h)
*/
public TreeNode inorderSuccessorViaRecursion(TreeNode root, TreeNode p) {
return find(root, null, p);
}
private TreeNode find(TreeNode current, TreeNode parent, TreeNode p) {
if (current == null) return parent;
return p.val >= current.val
? find(current.right, parent, p)
: find(current.left, current, p);
}
private static class TreeNode {
int val;
TreeNode left;
TreeNode right;
}
}