-
-
Save brianguertin/551e8dd00ece108abc83ff1adce9c0d4 to your computer and use it in GitHub Desktop.
Breadth-first tree traversal with Queue
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 java.util.*; | |
public class Main { | |
private static class Node { | |
public final char value; | |
public final Node left; | |
public final Node right; | |
public Node(char value, Node left, Node right) { | |
this.value = value; | |
this.left = left; | |
this.right = right; | |
} | |
} | |
/** | |
* -------A-------- | |
* -----/--\------- | |
* ----U----D------ | |
* --/--\----\----- | |
* -I----B----L---- | |
* -----/---------- | |
* ----E----------- | |
*/ | |
private static final Node TREE = new Node( | |
'A', new Node('U', new Node('I', null, null), new Node('B', new Node('E', null, null), null)), new Node('D', null, new Node('L', null, null)) | |
); | |
private static void printTree(Node root) { | |
final List<Node> all = new ArrayList<Node>(); | |
for (List<Node> children = Collections.singletonList(root); children.size() > 0; children = getDirectChildren(children)) { | |
all.addAll(children); | |
} | |
for (Node n : all) { | |
System.out.print(n.value); | |
} | |
System.out.println(); | |
} | |
private static List<Node> getDirectChildren(List<Node> nodes) { | |
final List<Node> children = new ArrayList<Node>(); | |
for (Node child : nodes) { | |
if (null != child.left) children.add(child.left); | |
if (null != child.right) children.add(child.right); | |
} | |
return children; | |
} | |
private static void printTreeWithQueue(Node root) { | |
final Queue<Node> queue = new LinkedList<Node>(); | |
queue.add(root); | |
while (!queue.isEmpty()) { | |
final Node next = queue.remove(); | |
System.out.print(next.value); | |
if (next.left != null) queue.add(next.left); | |
if (next.right != null) queue.add(next.right); | |
} | |
System.out.println(); | |
} | |
public static void main(String[] args) { | |
System.out.println("List:"); | |
printTree(TREE); | |
System.out.println("Queue:"); | |
printTreeWithQueue(TREE); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment