Vertical sum of binary tree in java

Previous
Next

If you want to practice data structure and algorithm programs, you can go through data structure and algorithm interview questions.

This is 10th part of java binary tree tutorial.

In this post, we will see how to print vertical sum of binary tree nodes in java. Below diagram will show vertical sum for binary tree.

Algorithm:

Steps for print vertical sum of binary tree:
  • Traverse tree in inorder traversal.
  • Create a variable level and initialise it with 0. When you traverse left child, decrease level by 1(level–) and when you traverse right child, increase level by 1(level++).
  • We need to maintain TreeMap with key as level and value as node data. If you get same key(level) again, then you need to add current node data to previous stored value to calculate sum.
    For example:
    TreeMap has entry with (0,40) where 0 is level and 40 is node data. So while traversing, if you encountered node 30 at level 0, so after processing node 30, TreeMap will have entry as (0,70)
  • Once TreeMap is populated after iterating all nodes, print the results.

Code for recursion will be:

Please find diagram below which shows level assigned for each binary tree node.

Example:

Lets create java program for printing vertical sum in binary tree:

Run above program and you will get following output:

Java Binary tree tutorial:

Previous
Next

Join Our News Letter - Stay Updated

Subscribe to Awesome Java Content.

Add Comment

Join Our News Letter - Stay Updated

Subscribe to Awesome Java Content.
You can like our facebook page Java2blog