print level wise nodes in the binary tree (Breadth First Traversal)

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:

    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>();
		while (!queue.isEmpty()) {
			BinaryNode node = queue.poll();
			if (node.left != null)
			if (node.right != null)

Output: 20, 15, 25, 12, 18, 22, 28


3 Responses to print level wise nodes in the binary tree (Breadth First Traversal)

  1. Pingback: algorithm to find left view and right view of binary tree in java | java tech stack

  2. cpanel vps says:

    Thanks very nice blog!|

  3. lprabak says:

    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.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


Mostly technology with occasional sprinkling of other random thoughts


Amir Amintabar's personal page

101 Books

Reading my way through Time Magazine's 100 Greatest Novels since 1923 (plus Ulysses)

Seek, Plunnge and more...

My words, my world...

ARRM Foundation

Do not wait for leaders; do it alone, person to person - Mother Teresa

Executive Management

An unexamined life is not worth living – Socrates

Diabolical or Smart

Nitwit, Blubber, Oddment, Tweak !!


A topnotch site


Just another site

coding algorithms

"An approximate answer to the right problem is worth a good deal more than an exact answer to an approximate problem." -- John Tukey