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