-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFindSuccessor2.java
More file actions
33 lines (30 loc) · 894 Bytes
/
FindSuccessor2.java
File metadata and controls
33 lines (30 loc) · 894 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
import java.util.*;
class Program {
// This is an input class. Do not edit.
static class BinaryTree {
public int value;
public BinaryTree left = null;
public BinaryTree right = null;
public BinaryTree parent = null;
public BinaryTree(int value) {
this.value = value;
}
}
// O(h) time | O(1) space
public BinaryTree findSuccessor(BinaryTree tree, BinaryTree node) {
// Write your code here.
if (node.right != null) {
BinaryTree curr = node.right;
while (curr.left != null) {
curr = curr.left;
}
return curr;
} else {
BinaryTree curr = node;
while (curr.parent != null && curr.parent.right == curr) {
curr = curr.parent;
}
return curr.parent;
}
}
}