Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Tree
  • Practice Tree
  • MCQs on Tree
  • Tutorial on Tree
  • Types of Trees
  • Basic operations
  • Tree Traversal
  • Binary Tree
  • Complete Binary Tree
  • Ternary Tree
  • Binary Search Tree
  • Red-Black Tree
  • AVL Tree
  • Full Binary Tree
  • B-Tree
  • Advantages & Disadvantages
Open In App
Next Article:
Find maximum vertical sum in binary tree
Next article icon

Vertical Sum in Binary Tree (Space Optimized)

Last Updated : 26 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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

Input:

Vertical-Taversal-


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

Vertical-Taversal--2

Approach:

We have discussed Hashing Based Solution in Vertical Sum in a given Binary Tree. Hashing based solution requires a Hash Table to be maintained. We know that hashing requires more space than the number of entries in it. In this post, Doubly Linked List based solution is discussed. The solution discussed here requires only n nodes of linked list where n is total number of vertical lines in binary tree.

Below is the implementation of the above approach: 

C++
// C++ program of space optimized solution // to find vertical sum of binary tree. #include <bits/stdc++.h>  using namespace std;  class TNode { public:     int data;     TNode *left, *right;   	TNode(int x){     	data = x;       	left = right = nullptr;     } };  class LNode { public:     int data;     LNode *prev, *next;   	LNode(int x){     	data = x;       	prev = next = nullptr;     } };   // Function that creates Linked list and store // vertical sum in it. void verticalSumDLLUtil(TNode* root, LNode* sumNode) {        // Update sum of current line by adding value     // of current tree node.     sumNode->data = sumNode->data + root->data;      // Recursive call to left subtree.     if (root->left) {         if (sumNode->prev == nullptr) {             sumNode->prev = new LNode(0);             sumNode->prev->next = sumNode;         }         verticalSumDLLUtil(root->left, sumNode->prev);     }      // Recursive call to right subtree.     if (root->right) {         if (sumNode->next == nullptr) {             sumNode->next = new LNode(0);             sumNode->next->prev = sumNode;         }         verticalSumDLLUtil(root->right, sumNode->next);     } }  // Function to print vertical sum of Tree. // It uses verticalSumDLLUtil() to calculate sum. vector<int> verticalSumDLL(TNode* root) {        // Create Linked list node for     // line passing through root.     LNode* sumNode = new LNode(0);      // Compute vertical sum of different lines.     verticalSumDLLUtil(root, sumNode);      // Make doubly linked list pointer point     // to first node in list.     while (sumNode->prev != nullptr) {         sumNode = sumNode->prev;     } 	   	vector<int> result;        // Print vertical sum of different lines     // of binary tree.     while (sumNode != nullptr) {       	result.push_back(sumNode->data);         sumNode = sumNode->next;     }   	return result; }  int main() {      	// Constructing binary tree.     //     //             1     //            / \     //           /   \     //          2     3     //         / \   / \     //        /   \ /   \     //       4    5 6    7     TNode* root = new TNode(1);     root->left = new TNode(2);     root->right = new TNode(3);     root->left->left = new TNode(4);     root->left->right = new TNode(5);     root->right->left = new TNode(6);     root->right->right = new TNode(7);      vector<int> res = verticalSumDLL(root);   	for(int i : res) {       	cout << i << " ";     }	     return 0; } 
C
// C program of space optimized solution // to find vertical sum of binary tree.  #include <stdio.h> #include <stdlib.h>  struct TNode {     int data;     struct TNode* left;     struct TNode* right; };  struct LNode {     int data;     struct LNode* prev;     struct LNode* next; };   struct TNode* createTNode(int data); struct LNode* createLNode(int data);  // Function that creates Linked list and stores // vertical sum in it. void verticalSumDLLUtil(struct TNode* root, struct LNode* sumNode) {        // Update sum of current line by adding value     // of current tree node.     sumNode->data += root->data;      // Recursive call to left subtree.     if (root->left != NULL) {         if (sumNode->prev == NULL) {             sumNode->prev = createLNode(0);             sumNode->prev->next = sumNode;         }         verticalSumDLLUtil(root->left, sumNode->prev);     }      // Recursive call to right subtree.     if (root->right != NULL) {         if (sumNode->next == NULL) {             sumNode->next = createLNode(0);             sumNode->next->prev = sumNode;         }         verticalSumDLLUtil(root->right, sumNode->next);     } }  // Function to print vertical sum of Tree. // It uses verticalSumDLLUtil() to calculate sum. void verticalSumDLL(struct TNode* root) {        // Create Linked list node for     // line passing through root.     struct LNode* sumNode = createLNode(0);      // Compute vertical sum of different lines.     verticalSumDLLUtil(root, sumNode);      // Move to the first node of the doubly   	// linked list     while (sumNode->prev != NULL) {         sumNode = sumNode->prev;     }      while (sumNode != NULL) {         printf("%d ", sumNode->data);         sumNode = sumNode->next;     } }  struct TNode* createTNode(int data) {     struct TNode* newNode =        	(struct TNode*)malloc(sizeof(struct TNode));     newNode->data = data;     newNode->left = newNode->right = NULL;     return newNode; }  struct LNode* createLNode(int data) {     struct LNode* newNode =        	(struct LNode*)malloc(sizeof(struct LNode));     newNode->data = data;     newNode->prev = newNode->next = NULL;     return newNode; }  int main() {        // Constructing binary tree.     //     //             1     //            / \     //           /   \     //          2     3     //         / \   / \     //        /   \ /   \     //       4    5 6    7     struct TNode* root = createTNode(1);     root->left = createTNode(2);     root->right = createTNode(3);     root->left->left = createTNode(4);     root->left->right = createTNode(5);     root->right->left = createTNode(6);     root->right->right = createTNode(7);        verticalSumDLL(root);      return 0; } 
Java
// Java program of space optimized solution // to find vertical sum of binary tree.  import java.util.*;  class TNode {     int data;     TNode left, right;     TNode(int x) {         data = x;         left = right = null;     } }  class LNode {     int data;     LNode prev, next;     LNode(int x) {         data = x;         prev = next = null;     } }  class GfG {      // Function that creates Linked list and stores     // vertical sum in it.     static void verticalSumDLLUtil(TNode root, LNode sumNode) {                // Update sum of current line by adding value         // of current tree node.         sumNode.data = sumNode.data + root.data;          // Recursive call to left subtree.         if (root.left != null) {             if (sumNode.prev == null) {                 sumNode.prev = new LNode(0);                 sumNode.prev.next = sumNode;             }             verticalSumDLLUtil(root.left, sumNode.prev);         }          // Recursive call to right subtree.         if (root.right != null) {             if (sumNode.next == null) {                 sumNode.next = new LNode(0);                 sumNode.next.prev = sumNode;             }             verticalSumDLLUtil(root.right, sumNode.next);         }     }      // Function to print vertical sum of Tree.     // It uses verticalSumDLLUtil() to calculate sum.     static List<Integer> verticalSumDLL(TNode root) {                // Create Linked list node for         // line passing through root.         LNode sumNode = new LNode(0);          // Compute vertical sum of        	// different lines.         verticalSumDLLUtil(root, sumNode);          // Make doubly linked list pointer point         // to first node in list.         while (sumNode.prev != null) {             sumNode = sumNode.prev;         }          List<Integer> result = new ArrayList<>();                while (sumNode != null) {             result.add(sumNode.data);             sumNode = sumNode.next;         }         return result;     }      public static void main(String[] args) {                // Constructing binary tree.         //         //             1         //            / \         //           /   \         //          2     3         //         / \   / \         //        /   \ /   \         //       4    5 6    7         TNode root = new TNode(1);         root.left = new TNode(2);         root.right = new TNode(3);         root.left.left = new TNode(4);         root.left.right = new TNode(5);         root.right.left = new TNode(6);         root.right.right = new TNode(7);          List<Integer> res = verticalSumDLL(root);         for (int i : res) {             System.out.print(i + " ");         }     } } 
Python
# Python program of space optimized solution # to find vertical sum of binary tree.  class TNode:     def __init__(self, x):         self.data = x         self.left = self.right = None  class LNode:     def __init__(self, x):         self.data = x         self.prev = self.next = None  # Function that creates Linked list and stores # vertical sum in it. def verticalSumDLLUtil(root, sumNode):        # Update sum of current line by adding value     # of current tree node.     sumNode.data += root.data      # Recursive call to left subtree.     if root.left:         if not sumNode.prev:             sumNode.prev = LNode(0)             sumNode.prev.next = sumNode         verticalSumDLLUtil(root.left, sumNode.prev)      # Recursive call to right subtree.     if root.right:         if not sumNode.next:             sumNode.next = LNode(0)             sumNode.next.prev = sumNode         verticalSumDLLUtil(root.right, sumNode.next)  # Function to print vertical sum of Tree. # It uses verticalSumDLLUtil() to calculate sum. def verticalSumDLL(root):        # Create Linked list node for     # line passing through root.     sumNode = LNode(0)      # Compute vertical sum of different lines.     verticalSumDLLUtil(root, sumNode)      # Make doubly linked list pointer point     # to first node in list.     while sumNode.prev:         sumNode = sumNode.prev      result = []          # Print vertical sum of different lines     # of binary tree.     while sumNode:         result.append(sumNode.data)         sumNode = sumNode.next      return result  # Constructing binary tree. # #             1 #            / \ #           /   \ #          2     3 #         / \   / \ #        /   \ /   \ #       4    5 6    7 root = TNode(1) root.left = TNode(2) root.right = TNode(3) root.left.left = TNode(4) root.left.right = TNode(5) root.right.left = TNode(6) root.right.right = TNode(7)  res = verticalSumDLL(root) print(" ".join(map(str, res))) 
C#
// C# program of space optimized solution // to find vertical sum of binary tree.  using System; using System.Collections.Generic;  class TNode {     public int data;     public TNode left, right;     public TNode(int x) {         data = x;         left = right = null;     } }  class LNode {     public int data;     public LNode prev, next;     public LNode(int x) {         data = x;         prev = next = null;     } }  class GfG {      // Function that creates Linked list and stores     // vertical sum in it.     static void verticalSumDLLUtil(TNode root, LNode sumNode) {                // Update sum of current line by adding value         // of current tree node.         sumNode.data = sumNode.data + root.data;          // Recursive call to left subtree.         if (root.left != null) {             if (sumNode.prev == null) {                 sumNode.prev = new LNode(0);                 sumNode.prev.next = sumNode;             }             verticalSumDLLUtil(root.left, sumNode.prev);         }          // Recursive call to right subtree.         if (root.right != null) {             if (sumNode.next == null) {                 sumNode.next = new LNode(0);                 sumNode.next.prev = sumNode;             }             verticalSumDLLUtil(root.right, sumNode.next);         }     }      // Function to print vertical sum of Tree.     // It uses verticalSumDLLUtil() to calculate sum.     static List<int> verticalSumDLL(TNode root) {                // Create Linked list node for         // line passing through root.         LNode sumNode = new LNode(0);          // Compute vertical sum of         // different lines.         verticalSumDLLUtil(root, sumNode);          // Make doubly linked list pointer point         // to first node in list.         while (sumNode.prev != null) {             sumNode = sumNode.prev;         }          List<int> result = new List<int>();          while (sumNode != null) {             result.Add(sumNode.data);             sumNode = sumNode.next;         }         return result;     }     	static void Main() {                // Constructing binary tree.         //         //             1         //            / \         //           /   \         //          2     3         //         / \   / \         //        /   \ /   \         //       4    5 6    7         TNode root = new TNode(1);         root.left = new TNode(2);         root.right = new TNode(3);         root.left.left = new TNode(4);         root.left.right = new TNode(5);         root.right.left = new TNode(6);         root.right.right = new TNode(7);          List<int> res = verticalSumDLL(root);         Console.WriteLine(string.Join(" ", res));     } } 
JavaScript
// JavaScript program of space optimized solution // to find vertical sum of binary tree.  // Tree node structure class TNode {     constructor(x) {         this.data = x;         this.left = this.right = null;     } }  // Doubly linked list structure class LNode {     constructor(x) {         this.data = x;         this.prev = this.next = null;     } }  // Function that creates Linked list and stores // vertical sum in it. function verticalSumDLLUtil(root, sumNode) {     // Update sum of current line by adding value     // of current tree node.     sumNode.data += root.data;      // Recursive call to left subtree.     if (root.left) {         if (!sumNode.prev) {             sumNode.prev = new LNode(0);             sumNode.prev.next = sumNode;         }         verticalSumDLLUtil(root.left, sumNode.prev);     }      // Recursive call to right subtree.     if (root.right) {         if (!sumNode.next) {             sumNode.next = new LNode(0);             sumNode.next.prev = sumNode;         }         verticalSumDLLUtil(root.right, sumNode.next);     } }  // Function to print vertical sum of Tree. // It uses verticalSumDLLUtil() to calculate sum. function verticalSumDLL(root) {     // Create Linked list node for     // line passing through root.     let sumNode = new LNode(0);      // Compute vertical sum of different lines.     verticalSumDLLUtil(root, sumNode);      // Make doubly linked list pointer point     // to first node in list.     while (sumNode.prev) {         sumNode = sumNode.prev;     }      const result = [];     // Print vertical sum of different lines     // of binary tree.     while (sumNode) {         result.push(sumNode.data);         sumNode = sumNode.next;     }     return result; }  // Constructing binary tree. // //             1 //            / \ //           /   \ //          2     3 //         / \   / \ //        /   \ /   \ //       4    5 6    7 const root = new TNode(1); root.left = new TNode(2); root.right = new TNode(3); root.left.left = new TNode(4); root.left.right = new TNode(5); root.right.left = new TNode(6); root.right.right = new TNode(7);  const res = verticalSumDLL(root); console.log(res.join(" ")); 

Output
4 2 12 3 7 

Time Complexity: O(n), where n is number of nodes in tree.
Auxiliary Space: O(h), where h Is the height of tree.



Next Article
Find maximum vertical sum in binary tree

R

Rahul Titare
Improve
Article Tags :
  • DSA
  • Tree
  • Amazon
Practice Tags :
  • Amazon
  • Tree

Similar Reads

  • Find maximum vertical sum in binary tree
    Given a binary tree, find the maximum vertical level sum in binary tree. Examples: Input : 3 / \ 4 6 / \ / \ -1 -2 5 10 \ 8 Output : 14Vertical level having nodes 6 and 8 has maximumvertical sum 14. Input : 1 / \ 5 8 / \ \ 2 -6 3 \ / -1 -4 \ 9Output : 4 A simple solution is to first find vertical le
    9 min read
  • Vertical Sum in a given Binary Tree
    Given a Binary Tree, find the vertical sum of the nodes that are in the same vertical line. Input: Output: 4 2 12 11 7 9Explanation: The below image shows the horizontal distances used to print vertical traversal starting from the leftmost level to the rightmost level. Table of Content Using map - O
    15 min read
  • Vertical Traversal of a Binary Tree
    Given a Binary Tree, the task is to find its vertical traversal starting from the leftmost level to the rightmost level. If multiple nodes pass through a vertical line, they should be printed as they appear in the level order traversal of the tree. Examples: Input: Output: [[4], [2], [1, 5, 6], [3,
    10 min read
  • Sum of all vertical levels of a Binary Tree
    Given a binary tree consisting of either 1 or 0 as its node values, the task is to find the sum of all vertical levels of the Binary Tree, considering each value to be a binary representation. Examples: Input: 1 / \ 1 0 / \ / \ 1 0 1 0Output: 7Explanation: Taking vertical levels from left to right:F
    10 min read
  • Vertical width of Binary tree | Set 2
    Given a binary tree, find the vertical width of the binary tree. The width of a binary tree is the number of vertical paths. Examples: Input : 7 / \ 6 5 / \ / \ 4 3 2 1 Output : 5 Input : 1 / \ 2 3 / \ / \ 4 5 6 7 \ \ 8 9 Output : 6 Prerequisite: Print Binary Tree in Vertical order In this image, th
    5 min read
  • Vertical width of Binary tree | Set 1
    Given a Binary tree, the task is to find the vertical width of the Binary tree. The width of a binary tree is the number of vertical paths in the Binary tree. Examples: Input: Output: 6Explanation: In this image, the tree contains 6 vertical lines which are the required width of the tree. Input : 7
    14 min read
  • Sum of nodes in top view of binary tree
    Top view of a binary tree is the set of nodes visible when the tree is viewed from the top. Given a binary tree, the task is to print the sum of nodes in top view.Examples: Input: 1 / \ 2 3 / \ \ 4 5 6 Output: 16 Input: 1 / \ 2 3 \ 4 \ 5 \ 6 Output: 12 Approach: The idea is to put nodes of same hori
    13 min read
  • Number of Isosceles triangles in a binary tree
    Pre-Requisites: Depth First Search | Parent Array RepresentationGiven a parent array representation of a binary tree, we need to find the number of Isosceles triangles in the binary tree. Consider a parent array representing a binary tree: Parent Array: Given below is the tree representation of the
    13 min read
  • Find if given vertical level of binary tree is sorted or not
    Given a binary tree. Find if a given vertical level of the binary tree is sorted or not. (For the case when two nodes are overlapping, check if they form a sorted sequence in the level they lie.)Prerequisite: Vertical Order Traversal Examples: Input : 1 / \ 2 5 / \ 7 4 / 6 Level l = -1 Output : YesN
    13 min read
  • Vertical Traversal of a Binary Tree using BFS
    Given a Binary Tree, the task is to find its vertical traversal starting from the leftmost level to the rightmost level. Note that if multiple nodes at same level pass through a vertical line, they should be printed as they appear in the level order traversal of the tree. Examples: Input: Output: [[
    9 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences