Table of Contents [hide]
If you want to practice data structure and algorithm programs, you can go through 100+ java coding 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.
Run above program and you will get following output:
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:
Java Binary tree tutorial:
- Binary tree in java
- Binary tree preorder traversal
- Binary tree postorder traversal
- Binary tree inorder traversal
- Binary tree level order traversal
- Binary tree spiral order traversal
- Binary tree reverse level order traversal
- Binary tree boundary traversal
- Print leaf nodes of binary tree
- Count leaf nodes in binary tree
- get maximum element in binary tree
- Print all paths from root to leaf in binary tree
- Print vertical sum of binary tree in java
- Get level of node in binary tree in java
- Lowest common ancestor(LCA) in binary tree in java
Was this post helpful?
Let us know if this post was helpful. Feedbacks are monitored on daily basis. Please do provide feedback as that\'s the only way to improve.