print level wise nodes in the binary tree (Breadth First Traversal)
May 2, 2013 3 Comments
This can be achieved using breadth first traversal algorithm.
– push level wise nodes into the queue at every iteration
– pop the node from queue at every iteration and print its value
Lets look at example:
20 15 25 12 18 22 28
BFS puts this tree in queue such there level wise nodes are placed one-another like this
-------------------------------- 20 | 15 | 25 | 12 | 18 | 22 | 28 --------------------------------
And at every loop element from queue is removed in FIFO manner
public void breadthFirstNonRecursive() { Queue<BinaryNode> queue = new java.util.LinkedList<BinaryNode>(); queue.offer(root); while (!queue.isEmpty()) { BinaryNode node = queue.poll(); System.out.println(node.element); if (node.left != null) queue.offer(node.left); if (node.right != null) queue.offer(node.right); } }
Output: 20, 15, 25, 12, 18, 22, 28
Pingback: algorithm to find left view and right view of binary tree in java | java tech stack
Thanks very nice blog!|
On the same tree output, I want to reverse the elements at each level and print. Eg. 12,18,22,28 are in level 2 ,I want to reverse and print as, 28,22,18,12 . Simillarly for Level 1 to be printed as, “25,15”, . Do you have solution for this.