Created
April 25, 2017 16:18
-
-
Save peterkos/4b71839acccf808db522417391f4db71 to your computer and use it in GitHub Desktop.
Generic tree with breadth-first search.
This file contains hidden or 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 static java.lang.System.*; | |
import java.util.ArrayList; | |
public class PCBTree { | |
public static void main(String[] args) { | |
/** | |
* BUILD THAT TREE! | |
* O | |
* /\ | |
* O O | |
* /\ | |
* O O | |
**/ | |
// Instantiate the root | |
Node<String> root = new Node<>("I am root", null, null); | |
// Instantiate all the children | |
Node<String> childOne = new Node<String>("I am child one", root, null); | |
Node<String> childTwo = new Node<String>("I am child two", root, null); | |
Node<String> grandChildOne = new Node<String>("I am grandchild one", childOne, null); | |
Node<String> grandChildTwo = new Node<String>("I am grandchild two", childOne, null); | |
// You are the father! | |
// (Adds corresponding children to their parents.) | |
root.addChildren(childOne, childTwo); | |
childOne.addChildren(grandChildOne, grandChildTwo); | |
// Breadth first search | |
root.breadthFirst(); | |
} | |
} | |
class Node<Element> { | |
public Element contents; | |
public Node<Element> parent; | |
public ArrayList<Node<Element>> children; | |
// Basic contructor | |
public Node(Element contents, Node<Element> parent, ArrayList<Node<Element>> children) { | |
this.contents = contents; | |
this.parent = parent; | |
// Checks to see if there are any children | |
// If not, give them a home | |
if (children == null) { | |
this.children = new ArrayList<Node<Element>>(); | |
} else { | |
this.children = children; | |
} | |
} | |
// Add many children by a variadic parameter | |
public void addChildren(Node<Element>... newChildren) { | |
for (Node<Element> child : newChildren) { | |
this.children.add(child); | |
} | |
} | |
// Breadth-first Traversal | |
public void breadthFirst() { | |
ArrayList<Node<Element>> queue = new ArrayList<>(); // Java 7 trick | |
// Treat the called node as root -- add to the queue | |
queue.add(this); | |
while (queue.size() != 0) { | |
// Remove the node | |
Node<Element> currentNode = queue.remove(0); | |
// "Visit" It (in our case, print its contents) | |
System.out.println(currentNode.contents); | |
// Adds its children to the queue (to visit later) | |
for (Node<Element> child : currentNode.children) { | |
queue.add(child); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment