Skip to content

Implementation of lowest common ancestor. #64

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Sep 5, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
before_script:
- sudo apt-get install ant-optional
- export OPTS="-server -Xmx3072M"
- export JAVA_OPTS="${JAVA_OPTS} ${OPTS}"
- export ANT_OPTS="${ANT_OPTS} ${OPTS}"
Expand All @@ -9,12 +10,12 @@ language: java

jdk:
- oraclejdk8
- oraclejdk7
# - oraclejdk7
# - oraclejdk6

# - openjdk8
- openjdk7
- openjdk6
# - openjdk6

env:
- TEST_SUITE=run_tests
Expand All @@ -27,4 +28,3 @@ env:
# - TEST_SUITE=sorts

script: "ant $TEST_SUITE"

3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ This is a collection of algorithms and data structures which I've implement over
* [Suffix Trie [backed by a Trie]](src/com/jwetherell/algorithms/data_structures/SuffixTrie.java)
* [Ternary Search Tree](src/com/jwetherell/algorithms/data_structures/TernarySearchTree.java)
* [Treap](src/com/jwetherell/algorithms/data_structures/Treap.java)
* [Tree](src/com/jwetherell/algorithms/data_structures/Tree.java)
* [Tree Map (associative array) [backed by an AVL Tree]](src/com/jwetherell/algorithms/data_structures/TreeMap.java)
* [Trie](src/com/jwetherell/algorithms/data_structures/Trie.java)
* [Trie Map (associative array) [backed by a Trie]](src/com/jwetherell/algorithms/data_structures/TrieMap.java)
Expand Down Expand Up @@ -156,6 +157,8 @@ This is a collection of algorithms and data structures which I've implement over
* [Edmonds Karp](src/com/jwetherell/algorithms/graph/EdmondsKarp.java)
* Matching
- [Turbo Matching](src/com/jwetherell/algorithms/graph/TurboMatching.java)
* [Lowest common ancestor in tree](src/com/jwetherell/algorithms/data_structures/Tree.java)


## Search
* Get index of value in array
Expand Down
167 changes: 167 additions & 0 deletions src/com/jwetherell/algorithms/data_structures/RootedTree.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,167 @@
package com.jwetherell.algorithms.data_structures;

import java.util.ArrayList;

/**
* Structure for storing rooted tree which allows to find lowest common ancestor.
*
* @param <T> type of value stored in nodes.
*/
public class RootedTree<T> {
private T value = null;
private int depth = 0;
private final ArrayList<RootedTree<T>> ancestors = new ArrayList<>();
private final ArrayList<RootedTree<T>> children = new ArrayList<>();

/**
* Exception which can be thrown by lowestCommonAncestor function if two
* nodes are in different trees.
*
*/
public static class NodesNotInSameTreeException extends Exception {}

/**
* Finds lower common ancestor of two nodes.
*
* Complexity O(log n) where n is the height of the tree.
*
* @param node1 first node
* @param node2 second node
* @return lower common ancestor
* @throws NodesNotInSameTreeException if nodes don't have common root
*/
public static <S> RootedTree<S> lowestCommonAncestor(RootedTree<S> node1, RootedTree<S> node2) throws NodesNotInSameTreeException {
if(node1 == node2) return node1;
else if(node1.depth < node2.depth) return lowestCommonAncestor(node2, node1);
else if(node1.depth > node2.depth) {
int diff = node1.depth - node2.depth;
int jump = 0;
while(diff > 0) {
if(diff % 2 == 1)
node1 = node1.ancestors.get(jump);
jump++;
diff /= 2;
}
return lowestCommonAncestor(node1, node2);
}
else {
try {
int step = 0;
while(1<<(step+1) <= node1.depth) step++;
while(step >= 0) {
if(step < node1.ancestors.size() && node1.ancestors.get(step) != node2.ancestors.get(step)) {
node1 = node1.ancestors.get(step);
node2 = node2.ancestors.get(step);
}
step--;
}
return node1.ancestors.get(0);
} catch (Exception e) {
throw new NodesNotInSameTreeException();
}

}

}

/**
* Creates tree with root only.
*
*/
public RootedTree() {

}

/**
* Cretes tree with root (storing value) only.
*
* @param value value to be stored in root
*/
public RootedTree(T value) {
this.value = value;
}

private RootedTree(RootedTree<T> parent) {
parent.children.add(this);
this.ancestors.add(parent);
this.depth = parent.depth + 1;
int dist = 0;
while(true) {
try {
this.ancestors.add(this.ancestors.get(dist).ancestors.get(dist));
dist++;
} catch (Exception e){
break;
}
}
}

public RootedTree<T> setValue(T value) {
this.value = value;
return this;
}

/**
* Creates new child for this node and returns it.
*
* Complexity O(log depth)
*
* @return added child
*/
public RootedTree<T> addChild() {
return new RootedTree<>(this);
}

/**
* Creates new child (storing value) for this node and returns it.
*
* Complexity O(log depth)
*
* @param value value to be stored in new child
* @return added child
*/
public RootedTree<T> addChild(T value) {
return addChild().setValue(value);
}

/**
* Returns value stored in node.
*
* @return node's value.
*/
public T getValue() {
return value;
}

/**
* Finds subtree with given value in the root.
*
* @param value value to be find
* @return subtree with given value in the root
*/
public RootedTree<T> find(T value) {
if(this.value == null) {
if(value == null)
return this;
}
else if(this.value.equals(value))
return this;
for(RootedTree<T> child: children) {
RootedTree<T> res = child.find(value);
if(res != null)
return res;
}
return null;
}

/**
* Returns true if tree contains a node with given value
*
* @param value to be checked
* @return true if tree contains node with given value, false otherwise
*/
public boolean contains(T value) {
return find(value) != null;
}

}
50 changes: 50 additions & 0 deletions test/com/jwetherell/algorithms/data_structures/RootedTreeTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
package com.jwetherell.algorithms.data_structures;

import org.junit.Test;

import static org.junit.Assert.*;

public class RootedTreeTest {

@Test
public void largeTreeTest() throws RootedTree.NodesNotInSameTreeException {
RootedTree<Integer> root = new RootedTree<>();
RootedTree<Integer> left = root.addChild();
RootedTree<Integer> middle = root.addChild();
RootedTree<Integer> right = root.addChild();

//long path
RootedTree<Integer> v = left;
for(int i = 0; i<1000; i++)
v = v.addChild();
RootedTree<Integer> leftRight = left.addChild();

assertEquals(RootedTree.lowestCommonAncestor(v, leftRight), left);

for(int i = 0; i<2000; i++) {
leftRight = leftRight.addChild();

assertEquals(RootedTree.lowestCommonAncestor(v, leftRight), left);
}

assertEquals(RootedTree.lowestCommonAncestor(middle, right), root);
assertEquals(RootedTree.lowestCommonAncestor(root, right), root);
assertEquals(RootedTree.lowestCommonAncestor(root, root), root);

RootedTree<Integer> root2 = new RootedTree<>();
boolean thrownException = false;
try {
RootedTree.lowestCommonAncestor(v, root2);
} catch (RootedTree.NodesNotInSameTreeException e) {
thrownException = true;
}
assertTrue(thrownException);

RootedTree<Integer> deepChild = v.addChild(101);
assertEquals(deepChild, root.find(101));
assertTrue(root.contains(101));

assertNull(root.find(102));
assertFalse(root.contains(102));
}
}