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
4d

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!
Add answer anonymously...
Snapdeal Software Engineer Interview Questions
Stay ahead in your career. Get AmbitionBox app
qr-code
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+

Reviews

4 L+

Interviews

4 Cr+

Salaries

1 Cr+

Users/Month

Contribute to help millions

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

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter