This post is completed by 1 user

  • 0
Add to List
Medium

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 Example

as 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

Code:


Output:

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



Also Read: