Created
April 9, 2019 11:47
-
-
Save ssaurel/04e88a5e16f6699775d6ab6086a94f6f to your computer and use it in GitHub Desktop.
Level Order Traversal Algorithm in Java for the SSaurel's Channel
This file contains 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
// 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