This post is completed by 1 user

  • 0
Add to List

Print The Top View of a Binary Tree

Objective: - Given a binary tree, print it in the Top View of it.

What is Top View: Top view means when you look at the tree from the top the nodes you will see will be called the top view of the tree. See the example below.

Print The Top View of a Binary Tree.
Print The Top View of a Binary Tree.

as you can see in the example above,8, 4, 2, 1, 3, 7 is the Top view of the given binary tree.


This approach is quite similar to the - Print the Binary Tree in Vertical Order Path. Just modified the code so that it will print only the first element it will encounter in the vertical order.

How will you know that you are visiting the first node at every level?

  1. Take a vari­able called level, when ever you go left, do level++ AND when ever you go right do level–.
  2. With the step above we have sep­a­rated out the lev­els vertically.
  3. Vertical-Order-Sum-Implementation
  4. Now all we need to do the level order traversal just to ensure that we will visit the top most node at level before we visit any other node at that level.
  5. We will use simple queue technique for level order traversal or BFS.
  6. we will create a class QueuePack, this will store the objects containing node and its level.
  7. See the code for a better understanding.



 1   2   3   4   7   8


Also Read: