Created
June 16, 2013 09:59
-
-
Save maxammann/5791580 to your computer and use it in GitHub Desktop.
LinkedTree
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.apache.commons.collections.iterators.ArrayIterator; | |
import java.util.Arrays; | |
import java.util.Iterator; | |
/** | |
* Represents a LinkedNode | |
*/ | |
public class LinkedNode<T> implements Iterable<LinkedNode<T>> { | |
private LinkedNode<T>[] children; | |
private int childrenCount = 0; | |
private T value; | |
public LinkedNode(T value) { | |
this.value = value; | |
} | |
public LinkedNode(T value, int childrenCount) { | |
this.value = value; | |
initialiseChildren(childrenCount); | |
} | |
public void setChildren(LinkedNode<T>... children) { | |
this.children = children; | |
} | |
public void setChildren(T... values) { | |
initialiseChildren(values.length); | |
for (int i = 0; i < children.length; i++) { | |
children[i].setValue(values[i]); | |
} | |
} | |
public LinkedNode<T> getNode(int index) { | |
return children[index]; | |
} | |
public LinkedNode<T>[] getNodes() { | |
return children; | |
} | |
public LinkedNode<T> addNode(LinkedNode<T> node) { | |
if (children == null) { | |
initialiseChildren(1); | |
} else if (childrenCount + 1 >= children.length){ | |
int newCapacity = children.length + 1; | |
children = Arrays.copyOf(children, newCapacity); | |
} | |
children[children.length - 1] = node; | |
childrenCount++; | |
return node; | |
} | |
public void setValue(T value) { | |
this.value = value; | |
} | |
public T getValue() { | |
return value; | |
} | |
@Override | |
@SuppressWarnings("unchecked") | |
public Iterator<LinkedNode<T>> iterator() { | |
return new ArrayIterator(children); | |
} | |
@SuppressWarnings("unchecked") | |
private void initialiseChildren(int size) { | |
this.children = new LinkedNode[size]; | |
} | |
public void createNode(int depth, LinkedNode<T> node) { | |
LinkedNode<T> current = this; | |
for (int i = 0; i < depth; i++) { | |
current = current.addNode(new LinkedNode<T>(null)); | |
} | |
if (current == null) { | |
current = new LinkedNode<T>(getValue()); | |
} | |
current.addNode(node); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment