-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNaryTree.java
More file actions
74 lines (62 loc) · 1.36 KB
/
NaryTree.java
File metadata and controls
74 lines (62 loc) · 1.36 KB
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
package ds;
import java.util.List;
/**
* Implementation of a generic NAry Tree.
*
* @author shivam.maharshi
*/
public class NaryTree<V> {
private V value;
private List<NaryTree<V>> nodes;
public NaryTree(V value) {
this.value = value;
}
public NaryTree<V> getParent() {
// TODO:
return null;
}
public int getDepth(NaryTree<V> node) {
int depth = 0;
NaryTree<V> root = this;
while (root != node) {
for (int i = 0; i < nodes.size(); i++) {
depth = getDepth(nodes.get(i)) + 1;
}
}
return depth;
}
/*
* Logic: Bring the deeper node to the same level. Move both nodes up till
* they are the same.
*/
public NaryTree<V> getLowestCommonAncestor(NaryTree<V> n1, NaryTree<V> n2) {
int n1Depth = getDepth(n1);
int n2Depth = getDepth(n2);
if (n1Depth > n2Depth) {
for (int i = 0; i < n1Depth - n2Depth; i++) {
n1 = n1.getParent();
}
} else {
for (int i = 0; i < n2Depth - n1Depth; i++) {
n2 = n2.getParent();
}
}
while (n1 != n2) {
n1 = n1.getParent();
n2 = n2.getParent();
}
return n1;
}
public V getValue() {
return value;
}
public void setValue(V value) {
this.value = value;
}
public List<NaryTree<V>> getNodes() {
return nodes;
}
public void setNodes(List<NaryTree<V>> nodes) {
this.nodes = nodes;
}
}