Tags: , ,

# Vertical sum of nodes in BST

Given a binary search tree, sum all the nodes which are on the same vertical line. This problem is known as a vertical sum problem. For example, given a binary tree as shown below the output will be:
Sum of vertical line 1 = 2
Sum of vertical line 2 = 3
Sum of vertical line 3 = 18
Sum of vertical line 4 = 8
Sum of vertical line 5 = 9

## Algorithm

To add the node to a particular line we have to reach that node. Question is what kind of traversal will be best suited for this problem? Imagine we have a binary that has only one level, root. It will be easy to say that the sum of the only vertical line is the root itself. What if there are two levels? Then we have three lines, first contains the left child of the root, second contains root itself, and third the right child.

As we increase the levels, the number of lines also increase and we can easily know that by moving the counter, increment it when we move to right and decrement when moving to left. So, it requires level order traversal of the binary tree.

```package AlgorithmsAndMe;
import java.util.*;

public class VerticalSum {
public Map<Integer,Integer> getVerticalSum(TreeNode root){

class VerticalInfo {
TreeNode node;
int line;

public VerticalInfo(TreeNode node, int line){
this.node = node;
this.line = line;
}
};

Map<Integer, Integer> verticalSum = new HashMap<>();

if(root == null) return verticalSum;

while (!queue.isEmpty()){
VerticalInfo current = queue.poll();
if(!verticalSum.containsKey(current.line)){
verticalSum.put(current.line,0);
}

/* add to the corresponding line */
verticalSum.put(current.line,
(int)verticalSum.get(current.line)
+ (int)current.node.getValue());

if(current.node.getLeft()!= null){
//decrrement the line number when moving left.
current.line-1)
);
}
if(current.node.getRight()!= null){
// Increment the line when moving right
The complexity of the above implementation will be `O(n)` because we traverse all the nodes if the tree at least once.