-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathNextNodeForBinarySearchTree.java
59 lines (52 loc) · 1.51 KB
/
NextNodeForBinarySearchTree.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
54
55
56
57
58
59
package by.andd3dfx.tree;
/**
* <pre>
* We have binary search tree:
*
* public interface Node {
* Node getParent();
* Node getLeft();
* Node getRight();
* }
*
* If item.value >= node.value - it belongs to right branch,
* If item.value < node.value - it belongs to left branch
*
* Write method next() to determine next node:
* public Node next(Node node) {
* ...
* }
* <pre/>
*
* @see <a href="https://youtu.be/qg0b9f8wGCg">Video solution</a>
*/
public class NextNodeForBinarySearchTree {
public interface Node {
Node getParent();
Node getLeft();
Node getRight();
}
public static Node next(Node node) {
if (node.getRight() != null) {
// Find left-most node of right child of 'node'
return findLeftMostNode(node.getRight());
}
// Go up by parents, until some transition will be left child of some node. If so - stop.
return findParentWithLeftTransition(node);
}
private static Node findLeftMostNode(Node node) {
if (node.getLeft() == null) {
return node;
}
return findLeftMostNode(node.getLeft());
}
private static Node findParentWithLeftTransition(Node node) {
if (node.getParent() == null) {
return node;
}
if (node.getParent().getLeft() == node) {
return node.getParent();
}
return findParentWithLeftTransition(node.getParent());
}
}