Vertical Sum in a Binary Tree

Last Updated : 29 Apr, 2026

Given a Binary Tree, find the vertical sum of the nodes that are in the same vertical line.

Example:

Input:

22

Output: 4 2 12 3 7
Explanation: The below image shows the horizontal distances used to print vertical traversal starting from the leftmost level to the rightmost level.

Vertical_Taversal_
Try It Yourself
redirect icon

[Naive Approach] Using map - O(n log n) Time and O(n) Space

We need to check the Horizontal Distances from the root for all nodes. If two nodes have the same Horizontal Distance (HD), then they are on the same vertical line. The idea of HD is simple. HD for root is 0, a right edge (edge connecting to right subtree) is considered as +1 horizontal distance and a left edge is considered as -1 horizontal distance. For example, in the above tree, HD for Node 4 is at -2, HD for Node 2 is -1, HD for 5 and 6 is 0 and HD for node 7 is +2. 

Algorithm:

  • Perform an in-order traversal starting from the root.
  • For each node, decrement HD by 1 for the left subtree and increment HD by 1 for the right subtree.
  • For each HD, add the node's value to a map that tracks the sum of nodes at each horizontal distance.
  • Once traversal is complete, extract and return the sums from the map in sorted order of HDs.
C++
// C++ program to find Vertical Sum in
// a given Binary Tree

#include<bits/stdc++.h>
using namespace std;

class Node {
public:
    int data;
    Node *left, *right;
	Node(int x){
     	data = x;
      	left = right = nullptr;
    }
};

// Traverses the tree in in-order form and
// populates a hashMap that contains the
// vertical sum
void verticalSumUtil(Node *node, int hd, map<int, int> &mp) {
  
    // Base case
    if (node == nullptr) return;

    // Recur for left subtree
    verticalSumUtil(node->left, hd-1, mp);

    // Add val of current node to
    // map entry of corresponding hd
    mp[hd] += node->data;

    // Recur for right subtree
    verticalSumUtil(node->right, hd+1, mp);
}

// Function to find vertical sum
vector<int> verticalSum(Node *root) {
  
    // a map to store sum of nodes for each 
    // horizontal distance
    map <int, int> mp;

    // populate the map
    verticalSumUtil(root, 0, mp);
	
  	vector<int> result;
    // Prints the values stored by VerticalSumUtil()
    for (auto it = mp.begin(); it != mp.end(); ++it) {
      	result.push_back(it->second);
    }
  	return result;
}

int main() {
  
    // Create binary tree as shown in above figure
  	//        1
  	//      /  \  
  	//     2    3
  	//    / \  / \
  	//   4   5 6  7
    Node *root = new Node(1);
    root->left = new Node(2);
    root->right = new Node(3);
    root->left->left = new Node(4);
    root->left->right = new Node(5);
    root->right->left = new Node(6);
    root->right->right = new Node(7);

    vector<int> res = verticalSum(root);
	for(int i : res) {
      	cout << i << " ";
    }
    return 0;
}
Java
// Java program to find Vertical Sum in a 
// given Binary Tree

import java.util.*;

class Node {
    int data;
    Node left, right;

    Node(int x) {
        data = x;
        left = right = null;
    }
}

class GfG {
  
    // Traverses the tree in in-order form and
    // populates a hashMap that contains the vertical sum
    static void verticalSumUtil(Node node, int hd,
                                Map<Integer, Integer> mp) {
      
        // Base case
        if (node == null)
            return;

        // Recur for left subtree
        verticalSumUtil(node.left, hd - 1, mp);

        // Add val of current node to map entry of
      	// corresponding hd
        mp.put(hd, mp.getOrDefault(hd, 0) + node.data);

        // Recur for right subtree
        verticalSumUtil(node.right, hd + 1, mp);
    }

    // Function to find vertical sum
    static List<Integer> verticalSum(Node root) {
      
        // A map to store sum of nodes for each
      	// horizontal distance
        Map<Integer, Integer> mp = new TreeMap<>();

        // Populate the map
        verticalSumUtil(root, 0, mp);

        // Collect the results
        List<Integer> result = new ArrayList<>();
        for (int sum : mp.values()) {
            result.add(sum);
        }
        return result;
    }

    public static void main(String[] args) {
      
        // Create binary tree as shown in above figure
        //        1
        //      /  \  
        //     2    3
        //    / \  / \
        //   4   5 6  7
        Node root = new Node(1);
        root.left = new Node(2);
        root.right = new Node(3);
        root.left.left = new Node(4);
        root.left.right = new Node(5);
        root.right.left = new Node(6);
        root.right.right = new Node(7);

        List<Integer> res = verticalSum(root);
        for (int i : res) {
            System.out.print(i + " ");
        }
    }
}
Python
# Python program to find Vertical Sum in
# a given Binary Tree

class Node:
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None

# Traverses the tree in in-order form and
# populates a hashMap that contains the vertical sum
def vertical_sum_util(node, hd, mp):
  
    # Base case
    if node is None:
        return

    # Recur for left subtree
    vertical_sum_util(node.left, hd - 1, mp)

    # Add val of current node to map entry of 
    # corresponding hd
    mp[hd] = mp.get(hd, 0) + node.data

    # Recur for right subtree
    vertical_sum_util(node.right, hd + 1, mp)

# Function to find vertical sum
def vertical_sum(root): 
  
    # A map to store sum of nodes for each 
    #horizontal distance
    mp = {}

    # Populate the map
    vertical_sum_util(root, 0, mp)

    # Collect the results
    result = [mp[hd] for hd in sorted(mp.keys())]
    return result

if __name__ == "__main__":
  
    # Create binary tree as shown in above figure
    #        1
    #      /  \  
    #     2    3
    #    / \  / \
    #   4   5 6  7
    root = Node(1)
    root.left = Node(2)
    root.right = Node(3)
    root.left.left = Node(4)
    root.left.right = Node(5)
    root.right.left = Node(6)
    root.right.right = Node(7)

    res = vertical_sum(root)
    for i in res:
        print(i, end=" ")
C#
// C# program to find Vertical Sum in
// a given Binary Tree

using System;
using System.Collections.Generic;

class Node {
    public int data;
    public Node left, right;

    public Node(int x) {
        data = x;
        left = right = null;
    }
}

class GfG {
  
    // Traverses the tree in in-order form and
    // populates a dictionary that contains the vertical sum
    static void VerticalSumUtil(Node node, int hd, 
                                Dictionary<int, int>mp) {
      
        // Base case
        if (node == null)
            return;

        // Recur for left subtree
        VerticalSumUtil(node.left, hd - 1, mp);

        // Add val of current node to map entry of
    	// corresponding hd
        if (!mp.ContainsKey(hd))
            mp[hd] = 0;
        mp[hd] += node.data;

        // Recur for right subtree
        VerticalSumUtil(node.right, hd + 1, mp);
    }

    // Function to find vertical sum
    static List<int> VerticalSum(Node root) {
      
        // A dictionary to store sum of nodes for each 
      	// horizontal distance
        Dictionary<int, int> mp = new Dictionary<int, int>();

        // Populate the map
        VerticalSumUtil(root, 0, mp);

        // Collect the results
        List<int> result = new List<int>();
        foreach (var key in new SortedSet<int>(mp.Keys)) {
            result.Add(mp[key]);
        }
        return result;
    }

    static void Main(string[] args) {
      
        // Create binary tree as shown in above figure
        //        1
        //      /  \  
        //     2    3
        //    / \  / \
        //   4   5 6  7
        Node root = new Node(1);
        root.left = new Node(2);
        root.right = new Node(3);
        root.left.left = new Node(4);
        root.left.right = new Node(5);
        root.right.left = new Node(6);
        root.right.right = new Node(7);

        List<int> res = VerticalSum(root);
        foreach (int i in res) {
            Console.Write(i + " ");
        }
    }
}
JavaScript
// JavaScript program to find Vertical Sum in a 
// given Binary Tree

class Node {
    constructor(data) {
        this.data = data;
        this.left = this.right = null;
    }
}

// Traverses the tree in in-order form and
// populates a hashMap that contains the vertical sum
function verticalSumUtil(node, hd, map) {

    // Base case
    if (node === null)
        return;

    // Recur for left subtree
    verticalSumUtil(node.left, hd - 1, map);

    // Add val of current node to map entry of 
    // corresponding hd
    map.set(hd, (map.get(hd) || 0) + node.data);

    // Recur for right subtree
    verticalSumUtil(node.right, hd + 1, map);
}

// Function to find vertical sum
function verticalSum(root) {

    // A map to store sum of nodes for each
    // horizontal distance
    let map = new Map();

    // Populate the map
    verticalSumUtil(root, 0, map);

    // Collect the results
    let result = [];
    [...map.entries()].sort((a, b) => a[0] - b[0]).forEach(([key, value]) => {
        result.push(value);
    });
    return result;
}

// Create binary tree as shown in above figure
//        1
//      /  \  
//     2    3
//    / \  / \
//   4   5 6  7
let root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
root.right.left = new Node(6);
root.right.right = new Node(7);

let res = verticalSum(root);
console.log(res.join(" "));

Output
4 2 12 3 7 

[Expected Approach] Using Hash map - O(n) Time and O(n) Space

The approach is same as above but here we are using hash map so time complexity will be reduces. Here we summing node values by their horizontal distance (hd) in a hash map, then return the vertical sums for each hd from minimum to maximum.

Algorithm:

  • Traverse the binary tree in-order, keeping track of the horizontal distance (hd) for each node.
  • For each node, add its value to a hashmap (mp) using the hd as the key.
  • Update the minimum and maximum hd values encountered during traversal.
  • After traversal, retrieve the sums from the map for all horizontal distances between the minimum and maximum hd values.
  • Return the list of vertical sums in order of their horizontal distances.
C++
// C++ program to find Vertical Sum in
// a given Binary Tree

#include<bits/stdc++.h>
using namespace std;

class Node {
public:
    int data;
    Node *left, *right;
	Node(int x){
     	data = x;
      	left = right = nullptr;
    }
};

// Traverses the tree in in-order form and
// populates a hashMap that contains the
// vertical sum
void verticalSumUtil(Node *node, int hd, unordered_map<int, int> &mp, 
                     int &mn, int &mx) {
    // Base case
    if (node == nullptr) return;

    // Recur for left subtree
    verticalSumUtil(node->left, hd-1, mp, mn, mx);

    // Add val of current node to
    // map entry of corresponding hd
    mp[hd] += node->data;
	mn = min(mn, hd);
  	mx = max(mx, hd);
  
    // Recur for right subtree
    verticalSumUtil(node->right, hd+1, mp, mn, mx);
}

// Function to find vertical sum
vector<int> verticalSum(Node *root) {
  
    // a map to store sum of nodes for each 
    // horizontal distance
    unordered_map <int, int> mp;
	
  	// mn is for storing the minimum hd
  	// mx is for storing the maximum hd
  	int mn = 0, mx = 0;
  
    // populate the map
    verticalSumUtil(root, 0, mp, mn, mx);
  	vector<int> result;
  
    for(int i = mn; i <= mx; i++) {
     	result.push_back(mp[i]); 
    }
  	return result;
}

int main() {
  
    // Create binary tree as shown in above figure
  	//        1
  	//      /  \  
  	//     2    3
  	//    / \  / \
  	//   4   5 6  7
    Node *root = new Node(1);
    root->left = new Node(2);
    root->right = new Node(3);
    root->left->left = new Node(4);
    root->left->right = new Node(5);
    root->right->left = new Node(6);
    root->right->right = new Node(7);

    vector<int> res = verticalSum(root);
	for(int i : res) {
      	cout << i << " ";
    }
    return 0;
}
Java
// Java program to find Vertical Sum in 
// a given Binary Tree

import java.util.*;

class Node {
    int data;
    Node left, right;

    Node(int x) {
        data = x;
        left = right = null;
    }
}

class GfG {
  
    // Traverses the tree in in-order form and
    // populates a hashMap that contains the vertical sum
    static void verticalSumUtil(Node node, int hd, 
                                Map<Integer, Integer> mp, 
                                 int[] minMax) {
        // Base case
        if (node == null) return;

        // Recur for left subtree
        verticalSumUtil(node.left, hd - 1, mp, minMax);

        // Add value of current node to map entry of
      	// corresponding hd
        mp.put(hd, mp.getOrDefault(hd, 0) + node.data);
        minMax[0] = Math.min(minMax[0], hd);
        minMax[1] = Math.max(minMax[1], hd);

        // Recur for right subtree
        verticalSumUtil(node.right, hd + 1, mp, minMax);
    }

    // Function to find vertical sum
    static List<Integer> verticalSum(Node root) {
      
        // a map to store sum of nodes for each
      	// horizontal distance
        Map<Integer, Integer> mp = new HashMap<>();
        int[] minMax = {0, 0};

        // populate the map
        verticalSumUtil(root, 0, mp, minMax);

        // Result
        List<Integer> result = new ArrayList<>();
        for (int i = minMax[0]; i <= minMax[1]; i++) {
            result.add(mp.get(i));
        }
        return result;
    }

    public static void main(String[] args) {
      
        // Create binary tree as shown in the above figure
        //        1
        //      /  \  
        //     2    3
        //    / \  / \
        //   4   5 6  7
        Node root = new Node(1);
        root.left = new Node(2);
        root.right = new Node(3);
        root.left.left = new Node(4);
        root.left.right = new Node(5);
        root.right.left = new Node(6);
        root.right.right = new Node(7);

        List<Integer> res = verticalSum(root);
        for (int i : res) {
            System.out.print(i + " ");
        }
    }
}
Python
# Python program to find Vertical Sum in 
# a given Binary Tree

class Node:
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None

# Traverses the tree in in-order form and
# populates a hashMap that contains the vertical sum
def vertical_sum_util(node, hd, mp, min_max):
  
    # Base case
    if node is None:
        return

    # Recur for left subtree
    vertical_sum_util(node.left, hd - 1, mp, min_max)

    # Add value of current node to map entry 
    # of corresponding hd
    mp[hd] = mp.get(hd, 0) + node.data
    min_max[0] = min(min_max[0], hd)
    min_max[1] = max(min_max[1], hd)

    # Recur for right subtree
    vertical_sum_util(node.right, hd + 1, mp, min_max)

# Function to find vertical sum
def vertical_sum(root):
    mp = {}
    min_max = [0, 0]

    # populate the map
    vertical_sum_util(root, 0, mp, min_max)

    result = []
    for i in range(min_max[0], min_max[1] + 1):
        result.append(mp[i])
    
    return result

if __name__ == "__main__":
  
    # Create binary tree as shown in the above figure
    #        1
    #      /  \  
    #     2    3
    #    / \  / \
    #   4   5 6  7
    root = Node(1)
    root.left = Node(2)
    root.right = Node(3)
    root.left.left = Node(4)
    root.left.right = Node(5)
    root.right.left = Node(6)
    root.right.right = Node(7)

    res = vertical_sum(root)
    for i in res:
        print(i, end=" ")
C#
// C# program to find Vertical Sum in a 
// given Binary Tree

using System;
using System.Collections.Generic;

class Node {
    public int data;
    public Node left, right;
    
    public Node(int x) {
        data = x;
        left = right = null;
    }
}

class GfG {
  
    // Traverses the tree in in-order form and
    // populates a hashMap that contains the vertical sum
    static void verticalSumUtil(Node node, int hd, Dictionary<int, int> mp, 
                                 ref int mn, ref int mx) {
        // Base case
        if (node == null) return;

        // Recur for left subtree
        verticalSumUtil(node.left, hd - 1, mp, ref mn, ref mx);

        // Add value of current node to map entry of 
      	// corresponding hd
        if (!mp.ContainsKey(hd))
            mp[hd] = 0;
        mp[hd] += node.data;
        mn = Math.Min(mn, hd);
        mx = Math.Max(mx, hd);

        // Recur for right subtree
        verticalSumUtil(node.right, hd + 1, mp, ref mn, ref mx);
    }

    // Function to find vertical sum
    static List<int> VerticalSum(Node root) {
      
        // a map to store sum of nodes for each
      	// horizontal distance
        Dictionary<int, int> mp = new Dictionary<int, int>();
        int mn = 0, mx = 0;

        // populate the map
        verticalSumUtil(root, 0, mp, ref mn, ref mx);

        List<int> result = new List<int>();
        for (int i = mn; i <= mx; i++) {
            result.Add(mp[i]);
        }
        return result;
    }

    static void Main() {
      
        // Create binary tree as shown in the above figure
        //        1
        //      /  \  
        //     2    3
        //    / \  / \
        //   4   5 6  7
        Node root = new Node(1);
        root.left = new Node(2);
        root.right = new Node(3);
        root.left.left = new Node(4);
        root.left.right = new Node(5);
        root.right.left = new Node(6);
        root.right.right = new Node(7);

        List<int> res = VerticalSum(root);
        foreach (int i in res) {
            Console.Write(i + " ");
        }
    }
}
JavaScript
// JavaScript program to find Vertical Sum in 
// a given Binary Tree

class Node {
    constructor(data) {
        this.data = data;
        this.left = this.right = null;
    }
}

// Traverses the tree in in-order form and
// populates a hashMap that contains the vertical sum
function verticalSumUtil(node, hd, mp, minMax) {

    // Base case
    if (node == null) return;

    // Recur for left subtree
    verticalSumUtil(node.left, hd - 1, mp, minMax);

    // Add value of current node to map entry 
    // of corresponding hd
    if (!mp.has(hd)) {
        mp.set(hd, 0);
    }
    mp.set(hd, mp.get(hd) + node.data);
    minMax[0] = Math.min(minMax[0], hd);
    minMax[1] = Math.max(minMax[1], hd);

    // Recur for right subtree
    verticalSumUtil(node.right, hd + 1, mp, minMax);
}

// Function to find vertical sum
function verticalSum(root) {
    let mp = new Map();
    let minMax = [0, 0];

    // populate the map
    verticalSumUtil(root, 0, mp, minMax);

    let result = [];
    for (let i = minMax[0]; i <= minMax[1]; i++) {
        result.push(mp.get(i));
    }
    return result;
}

// Create binary tree as shown in above figure
//        1
//      /  \  
//     2    3
//    / \  / \
//   4   5 6  7
let root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
root.right.left = new Node(6);
root.right.right = new Node(7);

let res = verticalSum(root);
console.log(res.join(" "));

Output
4 2 12 3 7 

[Alternate Approach] Using Doubly Linked List (Space Optimized) – O(n) Time and O(h) Space

The idea is to compute vertical sums without using a map or explicitly storing horizontal distances. A Doubly Linked List (DLL) is used where each node represents a vertical line of the binary tree.

While traversing the tree:

The value of each node is added to the current DLL node.
Moving to the left child corresponds to moving to the previous (prev) DLL node and adding value to the linked list node.
Moving to the right child corresponds to moving to the next (next) DLL node and adding value to the linked list node.
If the required DLL node does not exist, a new node is created.

In this way, the DLL grows dynamically and maintains the order of vertical lines implicitly. After traversal, we move to the leftmost DLL node and traverse towards the right to collect all vertical sums in order.

Consider the tree

22

Step 1: Create a DLL node head with value 0 for the root.
Call: verticalSumUtil(1, head)

Step 2: Add root value (1).
DLL: [1]

Step 3: Move to left child (2).

  • Create prev node and add 2.
  • DLL: [2] <-> [1]

Step 4: Move to left child (4).

  • Create another prev node and add 4.
  • DLL: [4] <-> [2] <-> [1]

Step 5: After node 4, recursion backtracks to node 2. Since left subtree is processed, move to right child (5). Node 5 lies in the same vertical line as root.

  • Add 5 → 1 + 5 = 6.
  • DLL: [4] <-> [2] <-> [6]

Step 6: Move to right child (3).

  • Create next node and add 3.
  • DLL: [4] <-> [2] <-> [6] <-> [3]

Step 7: Move to left child (6). It lies in the same vertical line as middle. Add 6 → 6 + 6 = 12.
DLL: [4] <-> [2] <-> [12] <-> [3]

Step 8: Move to right child (7).

  • Create next node and add 7.
  • DLL: [4] <-> [2] <-> [12] <-> [3] <-> [7]

After traversal: Move to the leftmost DLL node and traverse towards right to collect all vertical sums.

C++
#include <bits/stdc++.h>
using namespace std;

/* Define Node (REQUIRED for local compilation) */
struct Node {
    int data;
    Node *left, *right;

    Node(int val) {
        data = val;
        left = right = NULL;
    }
};

// DLL Node (represents a vertical line)
struct DLLNode {
    int data;
    DLLNode *prev, *next;

    DLLNode(int val) {
        data = val;
        prev = next = NULL;
    }
};

void verticalSumUtil(Node* root, DLLNode* curr) {
    if (root == NULL) return;

    curr->data += root->data;

    // Left subtree
    if (root->left) {
        if (curr->prev == NULL) {
            curr->prev = new DLLNode(0);
            curr->prev->next = curr;
        }
        verticalSumUtil(root->left, curr->prev);
    }

    // Right subtree
    if (root->right) {
        if (curr->next == NULL) {
            curr->next = new DLLNode(0);
            curr->next->prev = curr;
        }
        verticalSumUtil(root->right, curr->next);
    }
}

vector<int> verticalSum(Node *root) {
    if (root == NULL) return {};

    DLLNode* head = new DLLNode(0);

    verticalSumUtil(root, head);

    // Move to leftmost
    while (head->prev) {
        head = head->prev;
    }

    vector<int> res;

    while (head) {
        res.push_back(head->data);
        head = head->next;
    }

    return res;
}
// Driver Code 
int main() {
    // Constructing the Binary Tree
    //         1
    //       /   \
    //      2     3
    //     / \   / \\
    //    4   5 6   7
    Node *root = new Node(1);
    root->left = new Node(2);
    root->right = new Node(3);

    root->left->left = new Node(4);
    root->left->right = new Node(5);

    root->right->left = new Node(6);
    root->right->right = new Node(7);

    vector<int> res = verticalSum(root);

    for (int x : res) {
        cout << x << " ";
    }

    return 0;
}
C
#include <stdio.h>
#include <stdlib.h>

// Define Node (REQUIRED for local compilation)
struct Node {
    int data;
    struct Node *left, *right;
};

// DLL Node (represents a vertical line)
struct DLLNode {
    int data;
    struct DLLNode *prev, *next;
};

// Utility function
void verticalSumUtil(struct Node* root, struct DLLNode* curr) {
    if (root == NULL) return;

    curr->data += root->data;

    // Left subtree
    if (root->left) {
        if (curr->prev == NULL) {
            curr->prev = (struct DLLNode*)malloc(sizeof(struct DLLNode));
            curr->prev->next = curr;
            curr->prev->data = 0;
            curr->prev->prev = NULL;
        }
        verticalSumUtil(root->left, curr->prev);
    }

    // Right subtree
    if (root->right) {
        if (curr->next == NULL) {
            curr->next = (struct DLLNode*)malloc(sizeof(struct DLLNode));
            curr->next->prev = curr;
            curr->next->data = 0;
            curr->next->next = NULL;
        }
        verticalSumUtil(root->right, curr->next);
    }
}

// Main function
void verticalSum(struct Node *root, int *res, int *size) {
    if (root == NULL) return;

    struct DLLNode* head = (struct DLLNode*)malloc(sizeof(struct DLLNode));
    head->data = 0;
    head->prev = NULL;
    head->next = NULL;

    verticalSumUtil(root, head);

    // Move to leftmost
    while (head->prev) {
        head = head->prev;
    }

    int i = 0;
    while (head) {
        res[i++] = head->data;
        (*size)++;
        head = head->next;
    }
}

// Function to create a new Node
struct Node* newNode(int data) {
    struct Node* node = (struct Node*)malloc(sizeof(struct Node));
    node->data = data;
    node->left = NULL;
    node->right = NULL;
    return node;
}

// Driver Code
int main() {
    // Constructing the Binary Tree
    //         1
    //       /   \
    //      2     3
    //     / \   / \
    //    4   5 6   7
    struct Node *root = newNode(1);
    root->left = newNode(2);
    root->right = newNode(3);

    root->left->left = newNode(4);
    root->left->right = newNode(5);

    root->right->left = newNode(6);
    root->right->right = newNode(7);

    int res[100], size = 0;
    verticalSum(root, res, &size);

    for (int i = 0; i < size; i++) {
        printf("%d ", res[i]);
    }

    return 0;
}
Java
import java.util.LinkedList;
import java.util.List;

// Define Node (REQUIRED for local compilation)
class Node {
    int data;
    Node left, right;

    Node(int val) {
        data = val;
        left = right = null;
    }
}

class GfG {

    // DLL Node (represents a vertical line)
    static class DLLNode {
        int data;
        DLLNode prev, next;

        DLLNode(int val) {
            data = val;
            prev = next = null;
        }
    }

    // Utility function
    void verticalSumUtil(Node root, DLLNode curr) {
        if (root == null) return;

        curr.data += root.data;

        // Left subtree
        if (root.left!= null) {
            if (curr.prev == null) {
                curr.prev = new DLLNode(0);
                curr.prev.next = curr;
            }
            verticalSumUtil(root.left, curr.prev);
        }

        // Right subtree
        if (root.right!= null) {
            if (curr.next == null) {
                curr.next = new DLLNode(0);
                curr.next.prev = curr;
            }
            verticalSumUtil(root.right, curr.next);
        }
    }

    // Main function
    List<Integer> verticalSum(Node root) {
        if (root == null) return new LinkedList<>();

        DLLNode head = new DLLNode(0);

        verticalSumUtil(root, head);

        // Move to leftmost
        while (head.prev!= null) {
            head = head.prev;
        }

        List<Integer> res = new LinkedList<>();

        while (head!= null) {
            res.add(head.data);
            head = head.next;
        }

        return res;
    }
}

// Driver Code
public class Main {
    public static void main(String[] args) {
        // Constructing the Binary Tree
        //         1
        //       /   \
        //      2     3
        //     / \   / \
        //    4   5 6   7
        Node root = new Node(1);
        root.left = new Node(2);
        root.right = new Node(3);

        root.left.left = new Node(4);
        root.left.right = new Node(5);

        root.right.left = new Node(6);
        root.right.right = new Node(7);

        GfG obj = new GfG();
        List<Integer> res = obj.verticalSum(root);

        for (int x : res) {
            System.out.print(x + " ");
        }
    }
}
Python
from typing import List, Optional

# Tree Node
class Node:
    def __init__(self, val):
        self.data = val
        self.left = self.right = None


# DLL Node (represents a vertical line)
class DLLNode:
    def __init__(self, val):
        self.data = val
        self.prev = self.next = None


class Solution:
    
    # Utility function to fill vertical sums
    def verticalSumUtil(self, root: Optional[Node], curr: DLLNode):
        if root is None:
            return

        # Add current node value
        curr.data += root.data

        # Left subtree (move to prev)
        if root.left:
            if curr.prev is None:
                curr.prev = DLLNode(0)
                curr.prev.next = curr
            self.verticalSumUtil(root.left, curr.prev)

        # Right subtree (move to next)
        if root.right:
            if curr.next is None:
                curr.next = DLLNode(0)
                curr.next.prev = curr
            self.verticalSumUtil(root.right, curr.next)

    # Main function
    def verticalSum(self, root: Optional[Node]) -> List[int]:
        if root is None:
            return []

        head = DLLNode(0)

        # Build DLL
        self.verticalSumUtil(root, head)

        # Move to leftmost
        while head.prev:
            head = head.prev

        res = []

        # Traverse DLL
        while head:
            res.append(head.data)
            head = head.next

        return res


# Driver Code
if __name__ == "__main__":
    
    # Constructing the Binary Tree
    #         1
    #       /   \
    #      2     3
    #     / \   / \
    #    4   5 6   7

    root = Node(1)
    root.left = Node(2)
    root.right = Node(3)

    root.left.left = Node(4)
    root.left.right = Node(5)

    root.right.left = Node(6)
    root.right.right = Node(7)

    obj = Solution()
    res = obj.verticalSum(root)

    print(*res)
C#
using System;
using System.Collections.Generic;

// Define Node (REQUIRED for local compilation)
public class Node
{
    public int data;
    public Node left, right;

    public Node(int val)
    {
        data = val;
        left = right = null;
    }
}

public class Solution
{
    // DLL Node (represents a vertical line)
    public class DLLNode
    {
        public int data;
        public DLLNode prev, next;

        public DLLNode(int val)
        {
            data = val;
            prev = next = null;
        }
    }

    // Utility function
    public void verticalSumUtil(Node root, DLLNode curr)
    {
        if (root == null) return;

        curr.data += root.data;

        // Left subtree
        if (root.left!= null)
        {
            if (curr.prev == null)
            {
                curr.prev = new DLLNode(0);
                curr.prev.next = curr;
            }
            verticalSumUtil(root.left, curr.prev);
        }

        // Right subtree
        if (root.right!= null)
        {
            if (curr.next == null)
            {
                curr.next = new DLLNode(0);
                curr.next.prev = curr;
            }
            verticalSumUtil(root.right, curr.next);
        }
    }

    // Main function
    public List<int> verticalSum(Node root)
    {
        if (root == null) return new List<int>();

        DLLNode head = new DLLNode(0);

        verticalSumUtil(root, head);

        // Move to leftmost
        while (head.prev!= null)
        {
            head = head.prev;
        }

        List<int> res = new List<int>();

        while (head!= null)
        {
            res.Add(head.data);
            head = head.next;
        }

        return res;
    }
}

// Driver Code
public class Program
{
    public static void Main()
    {
        // Constructing the Binary Tree
        //         1
        //       /   \
        //      2     3
        //     / \   / \\
        //    4   5 6   7
        Node root = new Node(1);
        root.left = new Node(2);
        root.right = new Node(3);

        root.left.left = new Node(4);
        root.left.right = new Node(5);

        root.right.left = new Node(6);
        root.right.right = new Node(7);

        Solution obj = new Solution();

        List<int> res = obj.verticalSum(root);

        foreach (int x in res)
        {
            Console.Write(x + " ");
        }
    }
}
JavaScript
/* Define Node */
class Node {
    constructor(val) {
        this.data = val;
        this.left = this.right = null;
    }
}

// DLL Node (represents a vertical line)
class DLLNode {
    constructor(val) {
        this.data = val;
        this.prev = this.next = null;
    }
}

class Solution {

    verticalSumUtil(root, curr) {
        if (root === null) return;

        curr.data += root.data;

        // Left subtree
        if (root.left) {
            if (curr.prev === null) {
                curr.prev = new DLLNode(0);
                curr.prev.next = curr;
            }
            this.verticalSumUtil(root.left, curr.prev);
        }

        // Right subtree
        if (root.right) {
            if (curr.next === null) {
                curr.next = new DLLNode(0);
                curr.next.prev = curr;
            }
            this.verticalSumUtil(root.right, curr.next);
        }
    }

    verticalSum(root) {
        if (root === null) return [];

        let head = new DLLNode(0);

        this.verticalSumUtil(root, head);

        // Move to leftmost
        while (head.prev) {
            head = head.prev;
        }

        let res = [];

        while (head) {
            res.push(head.data);
            head = head.next;
        }

        return res;
    }
}

// Driver Code
let root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);

root.left.left = new Node(4);
root.left.right = new Node(5);

root.right.left = new Node(6);
root.right.right = new Node(7);

let obj = new Solution();
let res = obj.verticalSum(root);

console.log(res);  

Output
4 2 12 3 7 
Comment