Print the Vertical Sum in binary Tree .

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

What is Vertical Order Sum

Vertical Order Sum Exampleas you can see in the example above, [4],[2], [12],[3],[7] are the vertical order sum of the given binary tree.

Approach:

  • Do the inorder traversal.
  • Take a variable called level, when ever you fo 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 add the elements of each level, so create a TreeMap and the (key,value) pair will be (level,Sum of elements).
  • Vertical Order Sum Implementation

    Separate out the vertical levels

    At the end iterate through the TreeMap and print the results.

Complete Code:

Output:

Level -2 Sum : 7 
Level -1 Sum : 3 
Level 0 Sum : 12 
Level 1 Sum : 2 
Level 2 Sum : 4

__________________________________________________
Top Companies Interview Questions..-

Google Microsoft Amazon Facebook more..

If you find anything incorrect or you feel that there is any better approach to solve the above problem, please write comment.
__________________________________________________

%d bloggers like this: