Skip to content

Instantly share code, notes, and snippets.

@ssaurel
Created April 9, 2019 11:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ssaurel/04e88a5e16f6699775d6ab6086a94f6f to your computer and use it in GitHub Desktop.
Save ssaurel/04e88a5e16f6699775d6ab6086a94f6f to your computer and use it in GitHub Desktop.
Level Order Traversal Algorithm in Java for the SSaurel's Channel
// Level traversal (Breadth-first search)
public static <T> void levelOrderTraverse(Node<T> node) {
if (node == null)
return;
Queue<Node<T>> queue = new LinkedList<>();
// we add start node
queue.add(node);
// iterate while queue not empty
while(!queue.isEmpty()){
// dequeue and print data
Node<T> next = queue.remove();
System.out.print(next.data + " ");
// we add children nodes if not null
if(next.left!=null)
queue.add(next.left);
if(next.right!=null)
queue.add(next.right);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment