levelOrder(BinaryTree t) { if(t is not empty) { // enqueue current root queue.enqueue(t)
// while there are nodes to process while( queue is not empty ) { // dequeue next node BinaryTreetree= queue.dequeue();
process tree's root; // enqueue child elements from next level in order if( tree has non-empty left subtree ) { queue.enqueue( left subtree of t ) } if( tree has non-empty right subtree ) { queue.enqueue( right subtree of t ) } } } }
voidlevelOrder(Node root) { Queue<Node> queue = newLinkedList<Node>(); if (root != null) { // enqueue current root queue.offer(root);
// while there are nodes to process while (queue != null && queue.size() > 0) { // dequeue next node Nodetree= queue.poll();
System.out.print(tree.data + " ");
// enqueue child elements from next level in order if (tree.left != null){ queue.offer(tree.left); } if (tree.right != null){ queue.offer(tree.right); } } } }