Skip to content

Instantly share code, notes, and snippets.

@lnsp
Created December 22, 2014 23:20
Show Gist options
  • Save lnsp/f6032b264c4b801dce19 to your computer and use it in GitHub Desktop.
Save lnsp/f6032b264c4b801dce19 to your computer and use it in GitHub Desktop.
Simple tree structure
import java.util.ArrayList;
import java.util.List;
public class Node<T> {
private Node<T> parent;
private List<Node<T>> children;
private T data;
public Node(Node<T> parent) {
this(parent, null);
}
public Node(Node<T> parent, T data) {
this.parent = parent;
this.children = new ArrayList<Node<T>>();
if (this.parent != null)
this.parent.getChildren().add(this);
this.data = data;
}
public boolean hasParent() {
return parent != null;
}
public Node<T> getParent() {
return parent;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
public boolean hasChildren() {
return children.size() != 0;
}
public List<Node<T>> getChildren() {
return children;
}
}
public class Tree<T> {
private Node<T> root;
public Tree(T name) {
this.root = new Node<T>(null, name);
}
public Node<T> getRoot() {
return root;
}
public int size() {
return count(root);
}
private int count(Node<T> node) {
int count = 1;
for (Node<T> child : node.getChildren())
count += count(child);
return count;
}
private String toString(Node<T> node, int level) {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < level; i++) {
builder.append("-");
}
builder.append(node.getData() + System.lineSeperator());
for (Node<T> child : node.getChildren()) {
builder.append(toString(child, level + 1));
}
return builder.toString();
}
@Override
public String toString() {
return toString(root, 0);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment