Skip to content

Instantly share code, notes, and snippets.

@microaeris
Created November 4, 2015 11:47
Show Gist options
  • Save microaeris/0c94c3ff48b8c2f5b5d4 to your computer and use it in GitHub Desktop.
Save microaeris/0c94c3ff48b8c2f5b5d4 to your computer and use it in GitHub Desktop.
class Node {
public String value;
public LinkedList<Node> children;
public Node(String value, LinkedList<Node> children) {
this.value = value;
this.children = children != null ? children : new LinkedList<Node>();
}
}
public class TreeTraversal {
/**
* Prints out the nodes of a tree from top, down and left to right.
* This implementation doesn't use a queue.
* @param root
*/
public static void printTree(Node root) {
int maxDepth = maxDepth(root);
System.out.println("size of max depth: " + maxDepth);
for (int i = 0; i < maxDepth; i++) {
printLevel(root, i);
System.out.println("");
}
}
/**
*
* @param root
* @param depth to print
*/
public static void printLevel(Node root, int depth) {
if (depth == 1) {
System.out.print(root.value + " ");
}
for (Node c : root.children) {
printLevel(c, depth - 1);
}
}
public static int maxDepth(Node root) {
if (root.children.size() == 0) {
return 1;
}
int max = -1;
for (Node n : root.children) {
int d = maxDepth(n);
max = Math.max(max, d);
}
return 1 + max;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment