Print the Binary Tree in Vertical Order Path.

Objective: Given a binary tree, print it in vertical order path.

What is Vertical Order

Vertical Order Print Exampleas you can see in the example above, [4],[2], [1,5,6],[3],[7] are the verical order of the given binary tree.

Approach:

  • Its a tricky solution.
  • Do the preordertraversal.
  • Take a variable called level, when ever you go left, do level++ AND when ever you go right do level–.
  • With step above we have separated out the levels vertically.
  • Now you need to store the elements of each level, so create a TreeMap and the (key,value) pair will be (level,elements at that level).
  • At the end iterate through the TreeMap and print the results.
Separate out the vertical levels
Separate out the vertical levels

Complete Code:

Output:

[4]
[2]
[1, 5, 6]
[3]
[7]

9 thoughts on “Print the Binary Tree in Vertical Order Path.”

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

      Reply
  1. We use TreeMap here,to store natural ordering of elements. I think same is the case with std::Map in C++. Am i right?
    Also please upload c++ code also.

    Reply
      • Hey, for correct ordering we have to use level order traversal, pre order traversal will fail, if the left subtree is deep and nested, can shadow any of the right child. giving wrong ordering(bottom to top).

        Reply
  2. @tutorialhorizon:disqus Thanks for great posts ! I appreciate you taking time for writing all these ..
    a little clarification about the output , isn’t it supposed to be this
    [4]
    [2]
    [1, 5, 6] // this here instead of [5,1, 6 ]
    [3]
    [7]

    Reply
    • I have made changes in the code. instead of inorder traversal, using pre order traversal. Thanks Archit for the feedback.

      Reply

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.