-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnextNode.java
More file actions
37 lines (34 loc) · 812 Bytes
/
Copy pathnextNode.java
File metadata and controls
37 lines (34 loc) · 812 Bytes
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
// solution a
public static TreeNode findSuccessor(TreeNode node)
{
if (node == null)
return null;
if (node.getRight() != null)
return findMinimum(node.getRight());
TreeNode y = node.getParent();
TreeNode x = node;
while (y != null && x == y.getRight())
{
x = y;
y = y.getParent();
}
// Intuition: as we traverse left up the tree we traverse smaller values
// The first node on the right is the next larger number
return y;
}
//
public static TreeNode findPredecessor(TreeNode node)
{
if (node == null)
return null;
if (node.getLeft() != null)
return findMaximum(node.getLeft());
TreeNode parent = node.getParent();
TreeNode y = parent;
TreeNode x = node;
while (y != null && x == y.getLeft()) {
x = y;
y = y.getParent();
}
return y;
}