Reputation: 21
Can anyone suggest an algorithm to traverse a binary tree level by level starting from root?
Upvotes: 2
Views: 900
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
Reputation: 726579
That's done by breadth-first searching your tree:
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