Find Vertical Sum in a given Binary Tree

Given a binary tree, print vertical sum of it. Assume, the left and right child of a node makes 45 degree angle with the parent.


For example, vertical sum is shown in below binary tree

Vertical Sum Binary Tree


This problem can be easily solved with the help of Hashing. The idea is to create an empty map where each key represents the relative horizontal distance of a node from the root node and value in the map maintains sum of all nodes present at same horizontal distance. Then we do a pre-order traversal of the tree and we update the sum for current horizontal distance in the map. For each node, we recurse for its left subtree by decreasing horizontal distance by 1 and recurse for right subtree by increasing horizontal distance by 1.

Below figure shows horizontal distance and level of each node in above binary tree. The final values in the map will be

(horizontal distance -> vertical sum)

-1 -> 9
 0 -> 6
 1 -> 11
 2 -> 6

Horizontal distance vs Level - Binary Tree

C++ implementation –

Download   Run Complete Code

The time complexity of above solution is O(nlog(n)) and auxiliary space used by the program is O(n).

Exercise: Extend the solution to print nodes in vertical order.

Thanks for reading.

Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂

Get great deals at Amazon

Leave a Reply

Notify of