2

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

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Just thought I'd add that this obviously generalizes to k-ary ordered as well as general and thus unordered trees.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.