Given a Binary Tree, find the vertical sum of the nodes that are in the same vertical line.
Example:
Input:
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.
[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.
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>usingnamespacestd;classNode{public:intdata;Node*left,*right;Node(intx){data=x;left=right=nullptr;}};// Traverses the tree in in-order form and// populates a hashMap that contains the// vertical sumvoidverticalSumUtil(Node*node,inthd,map<int,int>&mp){// Base caseif(node==nullptr)return;// Recur for left subtreeverticalSumUtil(node->left,hd-1,mp);// Add val of current node to// map entry of corresponding hdmp[hd]+=node->data;// Recur for right subtreeverticalSumUtil(node->right,hd+1,mp);}// Function to find vertical sumvector<int>verticalSum(Node*root){// a map to store sum of nodes for each // horizontal distancemap<int,int>mp;// populate the mapverticalSumUtil(root,0,mp);vector<int>result;// Prints the values stored by VerticalSumUtil()for(autoit=mp.begin();it!=mp.end();++it){result.push_back(it->second);}returnresult;}intmain(){// Create binary tree as shown in above figure// 1// / \ // 2 3// / \ / \ // 4 5 6 7Node*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);vector<int>res=verticalSum(root);for(inti:res){cout<<i<<" ";}return0;}
Java
// Java program to find Vertical Sum in a // given Binary Treeimportjava.util.*;classNode{intdata;Nodeleft,right;Node(intx){data=x;left=right=null;}}classGfG{// Traverses the tree in in-order form and// populates a hashMap that contains the vertical sumstaticvoidverticalSumUtil(Nodenode,inthd,Map<Integer,Integer>mp){// Base caseif(node==null)return;// Recur for left subtreeverticalSumUtil(node.left,hd-1,mp);// Add val of current node to map entry of// corresponding hdmp.put(hd,mp.getOrDefault(hd,0)+node.data);// Recur for right subtreeverticalSumUtil(node.right,hd+1,mp);}// Function to find vertical sumstaticList<Integer>verticalSum(Noderoot){// A map to store sum of nodes for each// horizontal distanceMap<Integer,Integer>mp=newTreeMap<>();// Populate the mapverticalSumUtil(root,0,mp);// Collect the resultsList<Integer>result=newArrayList<>();for(intsum:mp.values()){result.add(sum);}returnresult;}publicstaticvoidmain(String[]args){// Create binary tree as shown in above figure// 1// / \ // 2 3// / \ / \// 4 5 6 7Noderoot=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);List<Integer>res=verticalSum(root);for(inti:res){System.out.print(i+" ");}}}
Python
# Python program to find Vertical Sum in# a given Binary TreeclassNode:def__init__(self,data):self.data=dataself.left=Noneself.right=None# Traverses the tree in in-order form and# populates a hashMap that contains the vertical sumdefvertical_sum_util(node,hd,mp):# Base caseifnodeisNone:return# Recur for left subtreevertical_sum_util(node.left,hd-1,mp)# Add val of current node to map entry of # corresponding hdmp[hd]=mp.get(hd,0)+node.data# Recur for right subtreevertical_sum_util(node.right,hd+1,mp)# Function to find vertical sumdefvertical_sum(root):# A map to store sum of nodes for each #horizontal distancemp={}# Populate the mapvertical_sum_util(root,0,mp)# Collect the resultsresult=[mp[hd]forhdinsorted(mp.keys())]returnresultif__name__=="__main__":# Create binary tree as shown in above figure# 1# / \ # 2 3# / \ / \# 4 5 6 7root=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)foriinres:print(i,end=" ")
C#
// C# program to find Vertical Sum in// a given Binary TreeusingSystem;usingSystem.Collections.Generic;classNode{publicintdata;publicNodeleft,right;publicNode(intx){data=x;left=right=null;}}classGfG{// Traverses the tree in in-order form and// populates a dictionary that contains the vertical sumstaticvoidVerticalSumUtil(Nodenode,inthd,Dictionary<int,int>mp){// Base caseif(node==null)return;// Recur for left subtreeVerticalSumUtil(node.left,hd-1,mp);// Add val of current node to map entry of// corresponding hdif(!mp.ContainsKey(hd))mp[hd]=0;mp[hd]+=node.data;// Recur for right subtreeVerticalSumUtil(node.right,hd+1,mp);}// Function to find vertical sumstaticList<int>VerticalSum(Noderoot){// A dictionary to store sum of nodes for each // horizontal distanceDictionary<int,int>mp=newDictionary<int,int>();// Populate the mapVerticalSumUtil(root,0,mp);// Collect the resultsList<int>result=newList<int>();foreach(varkeyinnewSortedSet<int>(mp.Keys)){result.Add(mp[key]);}returnresult;}staticvoidMain(string[]args){// Create binary tree as shown in above figure// 1// / \ // 2 3// / \ / \// 4 5 6 7Noderoot=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);List<int>res=VerticalSum(root);foreach(intiinres){Console.Write(i+" ");}}}
JavaScript
// JavaScript program to find Vertical Sum in a // given Binary TreeclassNode{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 sumfunctionverticalSumUtil(node,hd,map){// Base caseif(node===null)return;// Recur for left subtreeverticalSumUtil(node.left,hd-1,map);// Add val of current node to map entry of // corresponding hdmap.set(hd,(map.get(hd)||0)+node.data);// Recur for right subtreeverticalSumUtil(node.right,hd+1,map);}// Function to find vertical sumfunctionverticalSum(root){// A map to store sum of nodes for each// horizontal distanceletmap=newMap();// Populate the mapverticalSumUtil(root,0,map);// Collect the resultsletresult=[];[...map.entries()].sort((a,b)=>a[0]-b[0]).forEach(([key,value])=>{result.push(value);});returnresult;}// Create binary tree as shown in above figure// 1// / \ // 2 3// / \ / \// 4 5 6 7letroot=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);letres=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>usingnamespacestd;classNode{public:intdata;Node*left,*right;Node(intx){data=x;left=right=nullptr;}};// Traverses the tree in in-order form and// populates a hashMap that contains the// vertical sumvoidverticalSumUtil(Node*node,inthd,unordered_map<int,int>&mp,int&mn,int&mx){// Base caseif(node==nullptr)return;// Recur for left subtreeverticalSumUtil(node->left,hd-1,mp,mn,mx);// Add val of current node to// map entry of corresponding hdmp[hd]+=node->data;mn=min(mn,hd);mx=max(mx,hd);// Recur for right subtreeverticalSumUtil(node->right,hd+1,mp,mn,mx);}// Function to find vertical sumvector<int>verticalSum(Node*root){// a map to store sum of nodes for each // horizontal distanceunordered_map<int,int>mp;// mn is for storing the minimum hd// mx is for storing the maximum hdintmn=0,mx=0;// populate the mapverticalSumUtil(root,0,mp,mn,mx);vector<int>result;for(inti=mn;i<=mx;i++){result.push_back(mp[i]);}returnresult;}intmain(){// Create binary tree as shown in above figure// 1// / \ // 2 3// / \ / \ // 4 5 6 7Node*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);vector<int>res=verticalSum(root);for(inti:res){cout<<i<<" ";}return0;}
Java
// Java program to find Vertical Sum in // a given Binary Treeimportjava.util.*;classNode{intdata;Nodeleft,right;Node(intx){data=x;left=right=null;}}classGfG{// Traverses the tree in in-order form and// populates a hashMap that contains the vertical sumstaticvoidverticalSumUtil(Nodenode,inthd,Map<Integer,Integer>mp,int[]minMax){// Base caseif(node==null)return;// Recur for left subtreeverticalSumUtil(node.left,hd-1,mp,minMax);// Add value of current node to map entry of// corresponding hdmp.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 subtreeverticalSumUtil(node.right,hd+1,mp,minMax);}// Function to find vertical sumstaticList<Integer>verticalSum(Noderoot){// a map to store sum of nodes for each// horizontal distanceMap<Integer,Integer>mp=newHashMap<>();int[]minMax={0,0};// populate the mapverticalSumUtil(root,0,mp,minMax);// ResultList<Integer>result=newArrayList<>();for(inti=minMax[0];i<=minMax[1];i++){result.add(mp.get(i));}returnresult;}publicstaticvoidmain(String[]args){// Create binary tree as shown in the above figure// 1// / \ // 2 3// / \ / \// 4 5 6 7Noderoot=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);List<Integer>res=verticalSum(root);for(inti:res){System.out.print(i+" ");}}}
Python
# Python program to find Vertical Sum in # a given Binary TreeclassNode:def__init__(self,data):self.data=dataself.left=Noneself.right=None# Traverses the tree in in-order form and# populates a hashMap that contains the vertical sumdefvertical_sum_util(node,hd,mp,min_max):# Base caseifnodeisNone:return# Recur for left subtreevertical_sum_util(node.left,hd-1,mp,min_max)# Add value of current node to map entry # of corresponding hdmp[hd]=mp.get(hd,0)+node.datamin_max[0]=min(min_max[0],hd)min_max[1]=max(min_max[1],hd)# Recur for right subtreevertical_sum_util(node.right,hd+1,mp,min_max)# Function to find vertical sumdefvertical_sum(root):mp={}min_max=[0,0]# populate the mapvertical_sum_util(root,0,mp,min_max)result=[]foriinrange(min_max[0],min_max[1]+1):result.append(mp[i])returnresultif__name__=="__main__":# Create binary tree as shown in the above figure# 1# / \ # 2 3# / \ / \# 4 5 6 7root=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)foriinres:print(i,end=" ")
C#
// C# program to find Vertical Sum in a // given Binary TreeusingSystem;usingSystem.Collections.Generic;classNode{publicintdata;publicNodeleft,right;publicNode(intx){data=x;left=right=null;}}classGfG{// Traverses the tree in in-order form and// populates a hashMap that contains the vertical sumstaticvoidverticalSumUtil(Nodenode,inthd,Dictionary<int,int>mp,refintmn,refintmx){// Base caseif(node==null)return;// Recur for left subtreeverticalSumUtil(node.left,hd-1,mp,refmn,refmx);// Add value of current node to map entry of // corresponding hdif(!mp.ContainsKey(hd))mp[hd]=0;mp[hd]+=node.data;mn=Math.Min(mn,hd);mx=Math.Max(mx,hd);// Recur for right subtreeverticalSumUtil(node.right,hd+1,mp,refmn,refmx);}// Function to find vertical sumstaticList<int>VerticalSum(Noderoot){// a map to store sum of nodes for each// horizontal distanceDictionary<int,int>mp=newDictionary<int,int>();intmn=0,mx=0;// populate the mapverticalSumUtil(root,0,mp,refmn,refmx);List<int>result=newList<int>();for(inti=mn;i<=mx;i++){result.Add(mp[i]);}returnresult;}staticvoidMain(){// Create binary tree as shown in the above figure// 1// / \ // 2 3// / \ / \// 4 5 6 7Noderoot=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);List<int>res=VerticalSum(root);foreach(intiinres){Console.Write(i+" ");}}}
JavaScript
// JavaScript program to find Vertical Sum in // a given Binary TreeclassNode{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 sumfunctionverticalSumUtil(node,hd,mp,minMax){// Base caseif(node==null)return;// Recur for left subtreeverticalSumUtil(node.left,hd-1,mp,minMax);// Add value of current node to map entry // of corresponding hdif(!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 subtreeverticalSumUtil(node.right,hd+1,mp,minMax);}// Function to find vertical sumfunctionverticalSum(root){letmp=newMap();letminMax=[0,0];// populate the mapverticalSumUtil(root,0,mp,minMax);letresult=[];for(leti=minMax[0];i<=minMax[1];i++){result.push(mp.get(i));}returnresult;}// Create binary tree as shown in above figure// 1// / \ // 2 3// / \ / \// 4 5 6 7letroot=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);letres=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
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>usingnamespacestd;/* Define Node (REQUIRED for local compilation) */structNode{intdata;Node*left,*right;Node(intval){data=val;left=right=NULL;}};// DLL Node (represents a vertical line)structDLLNode{intdata;DLLNode*prev,*next;DLLNode(intval){data=val;prev=next=NULL;}};voidverticalSumUtil(Node*root,DLLNode*curr){if(root==NULL)return;curr->data+=root->data;// Left subtreeif(root->left){if(curr->prev==NULL){curr->prev=newDLLNode(0);curr->prev->next=curr;}verticalSumUtil(root->left,curr->prev);}// Right subtreeif(root->right){if(curr->next==NULL){curr->next=newDLLNode(0);curr->next->prev=curr;}verticalSumUtil(root->right,curr->next);}}vector<int>verticalSum(Node*root){if(root==NULL)return{};DLLNode*head=newDLLNode(0);verticalSumUtil(root,head);// Move to leftmostwhile(head->prev){head=head->prev;}vector<int>res;while(head){res.push_back(head->data);head=head->next;}returnres;}// Driver Code intmain(){// Constructing the Binary Tree// 1// / \ // 2 3// / \ / \\ // 4 5 6 7Node*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);vector<int>res=verticalSum(root);for(intx:res){cout<<x<<" ";}return0;}
C
#include<stdio.h>#include<stdlib.h>// Define Node (REQUIRED for local compilation)structNode{intdata;structNode*left,*right;};// DLL Node (represents a vertical line)structDLLNode{intdata;structDLLNode*prev,*next;};// Utility functionvoidverticalSumUtil(structNode*root,structDLLNode*curr){if(root==NULL)return;curr->data+=root->data;// Left subtreeif(root->left){if(curr->prev==NULL){curr->prev=(structDLLNode*)malloc(sizeof(structDLLNode));curr->prev->next=curr;curr->prev->data=0;curr->prev->prev=NULL;}verticalSumUtil(root->left,curr->prev);}// Right subtreeif(root->right){if(curr->next==NULL){curr->next=(structDLLNode*)malloc(sizeof(structDLLNode));curr->next->prev=curr;curr->next->data=0;curr->next->next=NULL;}verticalSumUtil(root->right,curr->next);}}// Main functionvoidverticalSum(structNode*root,int*res,int*size){if(root==NULL)return;structDLLNode*head=(structDLLNode*)malloc(sizeof(structDLLNode));head->data=0;head->prev=NULL;head->next=NULL;verticalSumUtil(root,head);// Move to leftmostwhile(head->prev){head=head->prev;}inti=0;while(head){res[i++]=head->data;(*size)++;head=head->next;}}// Function to create a new NodestructNode*newNode(intdata){structNode*node=(structNode*)malloc(sizeof(structNode));node->data=data;node->left=NULL;node->right=NULL;returnnode;}// Driver Codeintmain(){// Constructing the Binary Tree// 1// / \ // 2 3// / \ / \ // 4 5 6 7structNode*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);intres[100],size=0;verticalSum(root,res,&size);for(inti=0;i<size;i++){printf("%d ",res[i]);}return0;}
Java
importjava.util.LinkedList;importjava.util.List;// Define Node (REQUIRED for local compilation)classNode{intdata;Nodeleft,right;Node(intval){data=val;left=right=null;}}classGfG{// DLL Node (represents a vertical line)staticclassDLLNode{intdata;DLLNodeprev,next;DLLNode(intval){data=val;prev=next=null;}}// Utility functionvoidverticalSumUtil(Noderoot,DLLNodecurr){if(root==null)return;curr.data+=root.data;// Left subtreeif(root.left!=null){if(curr.prev==null){curr.prev=newDLLNode(0);curr.prev.next=curr;}verticalSumUtil(root.left,curr.prev);}// Right subtreeif(root.right!=null){if(curr.next==null){curr.next=newDLLNode(0);curr.next.prev=curr;}verticalSumUtil(root.right,curr.next);}}// Main functionList<Integer>verticalSum(Noderoot){if(root==null)returnnewLinkedList<>();DLLNodehead=newDLLNode(0);verticalSumUtil(root,head);// Move to leftmostwhile(head.prev!=null){head=head.prev;}List<Integer>res=newLinkedList<>();while(head!=null){res.add(head.data);head=head.next;}returnres;}}// Driver CodepublicclassMain{publicstaticvoidmain(String[]args){// Constructing the Binary Tree// 1// / \// 2 3// / \ / \// 4 5 6 7Noderoot=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);GfGobj=newGfG();List<Integer>res=obj.verticalSum(root);for(intx:res){System.out.print(x+" ");}}}
Python
fromtypingimportList,Optional# Tree NodeclassNode:def__init__(self,val):self.data=valself.left=self.right=None# DLL Node (represents a vertical line)classDLLNode:def__init__(self,val):self.data=valself.prev=self.next=NoneclassSolution:# Utility function to fill vertical sumsdefverticalSumUtil(self,root:Optional[Node],curr:DLLNode):ifrootisNone:return# Add current node valuecurr.data+=root.data# Left subtree (move to prev)ifroot.left:ifcurr.previsNone:curr.prev=DLLNode(0)curr.prev.next=currself.verticalSumUtil(root.left,curr.prev)# Right subtree (move to next)ifroot.right:ifcurr.nextisNone:curr.next=DLLNode(0)curr.next.prev=currself.verticalSumUtil(root.right,curr.next)# Main functiondefverticalSum(self,root:Optional[Node])->List[int]:ifrootisNone:return[]head=DLLNode(0)# Build DLLself.verticalSumUtil(root,head)# Move to leftmostwhilehead.prev:head=head.prevres=[]# Traverse DLLwhilehead:res.append(head.data)head=head.nextreturnres# Driver Codeif__name__=="__main__":# Constructing the Binary Tree# 1# / \# 2 3# / \ / \# 4 5 6 7root=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#
usingSystem;usingSystem.Collections.Generic;// Define Node (REQUIRED for local compilation)publicclassNode{publicintdata;publicNodeleft,right;publicNode(intval){data=val;left=right=null;}}publicclassSolution{// DLL Node (represents a vertical line)publicclassDLLNode{publicintdata;publicDLLNodeprev,next;publicDLLNode(intval){data=val;prev=next=null;}}// Utility functionpublicvoidverticalSumUtil(Noderoot,DLLNodecurr){if(root==null)return;curr.data+=root.data;// Left subtreeif(root.left!=null){if(curr.prev==null){curr.prev=newDLLNode(0);curr.prev.next=curr;}verticalSumUtil(root.left,curr.prev);}// Right subtreeif(root.right!=null){if(curr.next==null){curr.next=newDLLNode(0);curr.next.prev=curr;}verticalSumUtil(root.right,curr.next);}}// Main functionpublicList<int>verticalSum(Noderoot){if(root==null)returnnewList<int>();DLLNodehead=newDLLNode(0);verticalSumUtil(root,head);// Move to leftmostwhile(head.prev!=null){head=head.prev;}List<int>res=newList<int>();while(head!=null){res.Add(head.data);head=head.next;}returnres;}}// Driver CodepublicclassProgram{publicstaticvoidMain(){// Constructing the Binary Tree// 1// / \// 2 3// / \ / \\// 4 5 6 7Noderoot=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);Solutionobj=newSolution();List<int>res=obj.verticalSum(root);foreach(intxinres){Console.Write(x+" ");}}}
JavaScript
/* Define Node */classNode{constructor(val){this.data=val;this.left=this.right=null;}}// DLL Node (represents a vertical line)classDLLNode{constructor(val){this.data=val;this.prev=this.next=null;}}classSolution{verticalSumUtil(root,curr){if(root===null)return;curr.data+=root.data;// Left subtreeif(root.left){if(curr.prev===null){curr.prev=newDLLNode(0);curr.prev.next=curr;}this.verticalSumUtil(root.left,curr.prev);}// Right subtreeif(root.right){if(curr.next===null){curr.next=newDLLNode(0);curr.next.prev=curr;}this.verticalSumUtil(root.right,curr.next);}}verticalSum(root){if(root===null)return[];lethead=newDLLNode(0);this.verticalSumUtil(root,head);// Move to leftmostwhile(head.prev){head=head.prev;}letres=[];while(head){res.push(head.data);head=head.next;}returnres;}}// Driver Codeletroot=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);letobj=newSolution();letres=obj.verticalSum(root);console.log(res);