forked from maiquynhtruong/algorithms-and-problems
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsuccessor.java
27 lines (25 loc) · 855 Bytes
/
successor.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
/** Find the "next" node (in-order successor) of a given node in a binary search tree. Each node has a link to its parent**/
public class TreeNode {
int val;
TreeNode left, right, parent;
public TreeNode(int val) {this.val = val);
}
public class Solution {
public static TreeNode findSuccessor(TreeNode root) {
if (root.right != null) return findLeftmostNode(root.right);
else {
TreeNode parent = root.parent;
while (parent.val < root.val) {
parent = parent.parent;
}
return parent;
}
}
public static TreeNode findLeftmostNode(TreeNode root) {
if (root.left == null) return root;
while (root.left != null) root = root.left;
return root;
}
public static void main(String args[]) {
}
}