forked from Turingfly/cracking-the-coding-interview
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Successor.java
53 lines (50 loc) · 1.33 KB
/
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
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
package chapter04TreesAndGraphs;
/**
*
* Problem: Write an algorithm to find the "next" node (i.e., in-order
* successor) of a given node in a binary search tree. You may assume that each
* node has a link to its parent.
*
*/
public class Successor {
// with parent
/**
* public TreeNode inOrderSuccessor(TreeNode root) { if (root == null) {
* return null; } // Found right children -> return leftmost node of right
* subtree. if (root.right != null) { return leftMostchild(root.right); }
* else { TreeNode q = root; TreeNode x = q.parent; // Go up until we are on
* left instead of right while (x != null && x.left != q) { q = x; x =
* x.parent; } return x; } }
*
* private TreeNode leftMostchild(TreeNode root) { if (root == null) {
* return null; } while (root.left != null) { root = root.left; } return
* root; }
*/
// without parent
public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
if (root == null)
return null;
TreeNode next = null;
TreeNode cur = root;
while (cur != null && cur.val != p.val) {
if (cur.val > p.val) {
next = cur;
cur = cur.left;
} else {
cur = cur.right;
}
}
if (cur == null) {
return null;
}
if (cur.right != null) {
cur = cur.right;
while (cur.left != null) {
cur = cur.left;
}
return cur;
} else {
return next;
}
}
}