Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 34deeb9

Browse files
Merge pull request #64 from SzymonStankiewicz/tree
Implementation of lowest common ancestor.
2 parents 62bbfa2 + ce10dd9 commit 34deeb9

File tree

4 files changed

+220
-1
lines changed

4 files changed

+220
-1
lines changed

‎.travis.yml‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,4 +28,3 @@ env:
2828
# - TEST_SUITE=sorts
2929

3030
script: "ant $TEST_SUITE"
31-

‎README.md‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,7 @@ This is a collection of algorithms and data structures which I've implement over
6363
* [Suffix Trie [backed by a Trie]](src/com/jwetherell/algorithms/data_structures/SuffixTrie.java)
6464
* [Ternary Search Tree](src/com/jwetherell/algorithms/data_structures/TernarySearchTree.java)
6565
* [Treap](src/com/jwetherell/algorithms/data_structures/Treap.java)
66+
* [Tree](src/com/jwetherell/algorithms/data_structures/Tree.java)
6667
* [Tree Map (associative array) [backed by an AVL Tree]](src/com/jwetherell/algorithms/data_structures/TreeMap.java)
6768
* [Trie](src/com/jwetherell/algorithms/data_structures/Trie.java)
6869
* [Trie Map (associative array) [backed by a Trie]](src/com/jwetherell/algorithms/data_structures/TrieMap.java)
@@ -156,6 +157,8 @@ This is a collection of algorithms and data structures which I've implement over
156157
* [Edmonds Karp](src/com/jwetherell/algorithms/graph/EdmondsKarp.java)
157158
* Matching
158159
- [Turbo Matching](src/com/jwetherell/algorithms/graph/TurboMatching.java)
160+
* [Lowest common ancestor in tree](src/com/jwetherell/algorithms/data_structures/Tree.java)
161+
159162

160163
## Search
161164
* Get index of value in array
Lines changed: 167 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,167 @@
1+
package com.jwetherell.algorithms.data_structures;
2+
3+
import java.util.ArrayList;
4+
5+
/**
6+
* Structure for storing rooted tree which allows to find lowest common ancestor.
7+
*
8+
* @param <T> type of value stored in nodes.
9+
*/
10+
public class RootedTree<T> {
11+
private T value = null;
12+
private int depth = 0;
13+
private final ArrayList<RootedTree<T>> ancestors = new ArrayList<>();
14+
private final ArrayList<RootedTree<T>> children = new ArrayList<>();
15+
16+
/**
17+
* Exception which can be thrown by lowestCommonAncestor function if two
18+
* nodes are in different trees.
19+
*
20+
*/
21+
public static class NodesNotInSameTreeException extends Exception {}
22+
23+
/**
24+
* Finds lower common ancestor of two nodes.
25+
*
26+
* Complexity O(log n) where n is the height of the tree.
27+
*
28+
* @param node1 first node
29+
* @param node2 second node
30+
* @return lower common ancestor
31+
* @throws NodesNotInSameTreeException if nodes don't have common root
32+
*/
33+
public static <S> RootedTree<S> lowestCommonAncestor(RootedTree<S> node1, RootedTree<S> node2) throws NodesNotInSameTreeException {
34+
if(node1 == node2) return node1;
35+
else if(node1.depth < node2.depth) return lowestCommonAncestor(node2, node1);
36+
else if(node1.depth > node2.depth) {
37+
int diff = node1.depth - node2.depth;
38+
int jump = 0;
39+
while(diff > 0) {
40+
if(diff % 2 == 1)
41+
node1 = node1.ancestors.get(jump);
42+
jump++;
43+
diff /= 2;
44+
}
45+
return lowestCommonAncestor(node1, node2);
46+
}
47+
else {
48+
try {
49+
int step = 0;
50+
while(1<<(step+1) <= node1.depth) step++;
51+
while(step >= 0) {
52+
if(step < node1.ancestors.size() && node1.ancestors.get(step) != node2.ancestors.get(step)) {
53+
node1 = node1.ancestors.get(step);
54+
node2 = node2.ancestors.get(step);
55+
}
56+
step--;
57+
}
58+
return node1.ancestors.get(0);
59+
} catch (Exception e) {
60+
throw new NodesNotInSameTreeException();
61+
}
62+
63+
}
64+
65+
}
66+
67+
/**
68+
* Creates tree with root only.
69+
*
70+
*/
71+
public RootedTree() {
72+
73+
}
74+
75+
/**
76+
* Cretes tree with root (storing value) only.
77+
*
78+
* @param value value to be stored in root
79+
*/
80+
public RootedTree(T value) {
81+
this.value = value;
82+
}
83+
84+
private RootedTree(RootedTree<T> parent) {
85+
parent.children.add(this);
86+
this.ancestors.add(parent);
87+
this.depth = parent.depth + 1;
88+
int dist = 0;
89+
while(true) {
90+
try {
91+
this.ancestors.add(this.ancestors.get(dist).ancestors.get(dist));
92+
dist++;
93+
} catch (Exception e){
94+
break;
95+
}
96+
}
97+
}
98+
99+
public RootedTree<T> setValue(T value) {
100+
this.value = value;
101+
return this;
102+
}
103+
104+
/**
105+
* Creates new child for this node and returns it.
106+
*
107+
* Complexity O(log depth)
108+
*
109+
* @return added child
110+
*/
111+
public RootedTree<T> addChild() {
112+
return new RootedTree<>(this);
113+
}
114+
115+
/**
116+
* Creates new child (storing value) for this node and returns it.
117+
*
118+
* Complexity O(log depth)
119+
*
120+
* @param value value to be stored in new child
121+
* @return added child
122+
*/
123+
public RootedTree<T> addChild(T value) {
124+
return addChild().setValue(value);
125+
}
126+
127+
/**
128+
* Returns value stored in node.
129+
*
130+
* @return node's value.
131+
*/
132+
public T getValue() {
133+
return value;
134+
}
135+
136+
/**
137+
* Finds subtree with given value in the root.
138+
*
139+
* @param value value to be find
140+
* @return subtree with given value in the root
141+
*/
142+
public RootedTree<T> find(T value) {
143+
if(this.value == null) {
144+
if(value == null)
145+
return this;
146+
}
147+
else if(this.value.equals(value))
148+
return this;
149+
for(RootedTree<T> child: children) {
150+
RootedTree<T> res = child.find(value);
151+
if(res != null)
152+
return res;
153+
}
154+
return null;
155+
}
156+
157+
/**
158+
* Returns true if tree contains a node with given value
159+
*
160+
* @param value to be checked
161+
* @return true if tree contains node with given value, false otherwise
162+
*/
163+
public boolean contains(T value) {
164+
return find(value) != null;
165+
}
166+
167+
}
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
package com.jwetherell.algorithms.data_structures;
2+
3+
import org.junit.Test;
4+
5+
import static org.junit.Assert.*;
6+
7+
public class RootedTreeTest {
8+
9+
@Test
10+
public void largeTreeTest() throws RootedTree.NodesNotInSameTreeException {
11+
RootedTree<Integer> root = new RootedTree<>();
12+
RootedTree<Integer> left = root.addChild();
13+
RootedTree<Integer> middle = root.addChild();
14+
RootedTree<Integer> right = root.addChild();
15+
16+
//long path
17+
RootedTree<Integer> v = left;
18+
for(int i = 0; i<1000; i++)
19+
v = v.addChild();
20+
RootedTree<Integer> leftRight = left.addChild();
21+
22+
assertEquals(RootedTree.lowestCommonAncestor(v, leftRight), left);
23+
24+
for(int i = 0; i<2000; i++) {
25+
leftRight = leftRight.addChild();
26+
27+
assertEquals(RootedTree.lowestCommonAncestor(v, leftRight), left);
28+
}
29+
30+
assertEquals(RootedTree.lowestCommonAncestor(middle, right), root);
31+
assertEquals(RootedTree.lowestCommonAncestor(root, right), root);
32+
assertEquals(RootedTree.lowestCommonAncestor(root, root), root);
33+
34+
RootedTree<Integer> root2 = new RootedTree<>();
35+
boolean thrownException = false;
36+
try {
37+
RootedTree.lowestCommonAncestor(v, root2);
38+
} catch (RootedTree.NodesNotInSameTreeException e) {
39+
thrownException = true;
40+
}
41+
assertTrue(thrownException);
42+
43+
RootedTree<Integer> deepChild = v.addChild(101);
44+
assertEquals(deepChild, root.find(101));
45+
assertTrue(root.contains(101));
46+
47+
assertNull(root.find(102));
48+
assertFalse(root.contains(102));
49+
}
50+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /