Vertical Sum in a Binary Tree

Given a binary tree where each node has a positive integer value, compute the vertical sum of the nodes. The vertical sum is defined as the sum of all nodes aligned along the same vertical line in the tree.

Explanation:

A binary tree is a structure where each parent node has no more than two child nodes. The task is to sum up the node values that lie on the same vertical line from the top to the bottom of the tree.

Input:
The input starts with an integer ‘T’ representing the number of test cases. Each test case consists of tree nodes presented in level order, where each node's value is separated by a space. If a node lacks a left or right child, it is denoted by -1 in its position.
Output:
For each test case, output the vertical sum of the binary tree's nodes as a sequence of numbers separated by spaces on a new line for each test case.

Example:

Consider the following Binary Tree:

sample-tree

Output the vertical sum: 12 9 11 6

Constraints:

  • 1 <= T <= 100
  • 1 <= N <= 3000
  • 1 <= node data <= 10^9
  • Time Limit: 1sec

Note:

The function handles the printing automatically. Implement the function to return the vertical sums as required.

AnswerBot
4mo

Compute the vertical sum of nodes in a binary tree aligned along the same vertical line.

  • Traverse the binary tree in a level order manner to calculate the vertical sum.

  • Use a hashmap to store the vertic...read more

Help your peers!
Select
Add answer anonymously...

Snapdeal Software Engineer interview questions & answers

A Software Engineer was asked Q. Given an array, find a pair of elements.
A Software Engineer was asked Q. Given a binary tree, return the vertical sum of the tree.
A Software Engineer was asked Q. How many rectangles/squares are there on a chessboard?

Popular interview questions of Software Engineer

A Software Engineer was asked Q1. Given an array, find a pair of elements.
A Software Engineer was asked Q2. Given a binary tree, return the vertical sum of the tree.
A Software Engineer was asked Q3. How many rectangles/squares are there on a chessboard?
Snapdeal Software Engineer Interview Questions
Stay ahead in your career. Get AmbitionBox app
play-icon
play-icon
qr-code
Trusted by over 1.5 Crore job seekers to find their right fit company
80 L+

Reviews

10L+

Interviews

4 Cr+

Salaries

1.5 Cr+

Users

Contribute to help millions

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2025 Info Edge (India) Ltd.

Follow Us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter
Profile Image
Hello, Guest
AmbitionBox Employee Choice Awards 2025
Winners announced!
awards-icon
Contribute to help millions!
Write a review
Write a review
Share interview
Share interview
Contribute salary
Contribute salary
Add office photos
Add office photos
Add office benefits
Add office benefits