forked from oleg-cherednik/DailyCodingProblem
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.java
85 lines (67 loc) · 2.32 KB
/
Solution.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import java.util.Map;
import java.util.TreeMap;
/**
* @author Oleg Cherednik
* @since 13.02.2019
*/
public class Solution {
public static void main(String... args) {
Map<Integer, Node> map = createTree();
System.out.println(5 + " -> " + inorderSuccessor(map.get(5)).data); // 10
System.out.println(10 + " -> " + inorderSuccessor(map.get(10)).data); // 22
System.out.println(22 + " -> " + inorderSuccessor(map.get(22)).data); // 25
System.out.println(25 + " -> " + inorderSuccessor(map.get(25)).data); // 30
System.out.println(30 + " -> " + inorderSuccessor(map.get(30)).data); // 35
System.out.println(35 + " -> " + inorderSuccessor(map.get(35))); // null
}
private static Map<Integer, Node> createTree() {
Node five = new Node(5);
Node ten = new Node(10);
Node twentyTwo = new Node(22);
Node thirty = new Node(30);
Node thirtyFive = new Node(35);
Node twentyFive = new Node(25);
twentyTwo.right = twentyFive;
twentyFive.parent = twentyTwo;
twentyTwo.parent = thirty;
thirtyFive.parent = thirty;
thirty.parent = ten;
thirty.left = twentyTwo;
thirty.right = thirtyFive;
five.parent = ten;
ten.left = five;
ten.right = thirty;
Map<Integer, Node> map = new TreeMap<>();
map.put(five.data, five);
map.put(ten.data, ten);
map.put(twentyTwo.data, twentyTwo);
map.put(twentyFive.data, twentyFive);
map.put(thirty.data, thirty);
map.put(thirtyFive.data, thirtyFive);
return map;
}
public static Node inorderSuccessor(Node node) {
if (node == null)
return null;
if (node.right != null) {
node = node.right;
while (node.left != null)
node = node.left;
return node;
}
if (node.parent == null)
return null;
while (node.parent != null && node.parent.left != node)
node = node.parent;
return node.parent;
}
private static final class Node {
private final int data;
private Node parent;
private Node left;
private Node right;
public Node(int data) {
this.data = data;
}
}
}