Show Buttons
Share On Facebook
Share On Twitter
Share On Google Plus
Share On Linkdin
Share On Pinterest
Share On Reddit
Share On Stumbleupon
Contact us
Hide Buttons

Print the Binary Tree in Vertical Order Path.

Objec­tive: - Given a binary tree, print it in ver­ti­cal order path.

What is Ver­ti­cal Order



as you can see in the exam­ple above, [4],[2], [1,5,6],[3],[7] are the ver­i­cal order of the given binary tree.


  • Its a tricky solution.
  • Do the inorder traversal.
  • Take a vari­able called level, when ever you go left, do level++ AND when ever you go right do level–.
  • With step above we have sep­a­rated out the lev­els vertically.
  • Now you need to store the ele­ments of each level, so cre­ate a TreeMap and the (key,value) pair will be (level,elements at that level).
  • At the end iter­ate through the TreeMap and print the results.


Com­plete Code:


[5, 1, 6]

You may also like...

  • user_2005

    did not under­stand :
    Node y = vertical(root.left, –level);

    • tuto­ri­al­hori­zon

      sorry for the late reply. as it is explained in the arti­cle that when ever we go to left or right we need to keep track of the level we are in

  • Ankita

    Its print­ing [5,1,6] not [6,1,5]

    • tuto­ri­al­hori­zon

      Thanks ankita, though the pro­gram is still cor­rect, I have cor­rected the output.

  • shaik­suraz

    We use TreeMap here,to store nat­ural order­ing of ele­ments. I think same is the case with std::Map in C++. Am i right?
    Also please upload c++ code also.