This post is completed by 1 user

  • 0
Add to List
Medium

76. Calculate Vertical Sum in Binary Tree

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

What is Vertical Order Sum

as 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, whenever you go left, do level++ AND whenever you go right do level--.
  • With the step above we have separated the levels vertically.
  • Now you need to add the elements of each level, so create a dictionary and store the level as the key and the sum of elements at the same level as the value.
  • At the end iterate through the dictionary and print the results
 

Output:

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