murat
murat

Reputation: 21

Algorithm to traverse a binary tree level by level starting from root

Can anyone suggest an algorithm to traverse a binary tree level by level starting from root?

Upvotes: 2

Views: 900

Answers (2)

smitec
smitec

Reputation: 3049

You can perform this kind of traversal using a queue. From the root node push its children to the end of a queue, then while the queue is not empty pop an item from the top of the queue and add its children to the end of the queue. Processing each node where appropriate.

This is essentially a Breadth First Traversal.

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726579

That's done by breadth-first searching your tree:

  • Create a queue of tree nodes
  • Enqueue the tree root
  • While the queue is not empty, repeat the following:
  • Dequeue a node, and print its content
  • Enqueue the left sub-node of the current node
  • Enqueue the right sub-node of the current node

When you follow this algorithm, all nodes from level K will be printed prior to printing the first node from level K+1, so the tree will be printed level-by-level.

Upvotes: 5

Related Questions