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

For example, the vertical sum is shown in the following binary tree:

 
Vertical Sum Binary Tree

Practice this problem

1. Using Hashing

We can easily solve this problem 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 the value in the map maintains the sum of all nodes present at the same horizontal distance. Then perform preorder traversal on the tree, and update the sum for the current horizontal distance in the map. For each node, recur for its left subtree by decreasing horizontal distance by one, and recur for the right subtree by increasing horizontal distance by one.

The following figure shows the horizontal distance and level of each node in the 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

Following is the C++, Java, and Python program that demonstrates it:

C++


Download  Run Code

Output:

9 6 11 6

Java


Download  Run Code

Output:

9 6 11 6

Python


Download  Run Code

Output:

9 6 11 6

The time complexity of the above solution is O(n.log(n)) and requires O(n) extra space, where n is the size of the binary tree.

 
Exercise: Reduce time complexity to linear using std::unordered_map/HashMap.

2. Using Auxiliary Data Structure

We can improve the time complexity of the above solution to linear by using a doubly-linked list data structure. The idea is to store the vertical sum of the binary tree in a doubly-linked list, where each node of the doubly linked list stores the sum of all nodes corresponding to a vertical line in a binary tree.

We start by constructing a doubly linked list node that stores the sum of nodes present at the vertical line passing through the root node. Then node->prev and node->next will correspond to the sum of nodes present at the vertical line passing through the root node’s left and right child, respectively. The trick is to recursively construct the linked list and update nodes with the vertical sums as we traverse the tree.

The algorithm can be implemented as follows in C++, Java, and Python:

C++


Download  Run Code

Output:

9 6 11 6

Java


Download  Run Code

Output:

9 6 11 6

Python


Download  Run Code

Output:

9 6 11 6

The time complexity of the above solution is O(n), where n is the total number of nodes in the binary tree. The auxiliary space required by the program is O(n) for linked list nodes.

 
Exercise: Extend the solution to print nodes in vertical order