Convert a Binary Tree to its Sum Tree

Given a binary tree of integers, convert it to a sum tree where each node is replaced by the sum of the values of its left and right subtrees. Set leaf nodes to zero.

Input:

The first line contains an integer 'T', the number of test cases.
For each test case, a line with elements in level order, with nodes separated by spaces. Use -1 for null nodes.

Output:

For each test case, return the level order traversal of the converted sum tree, with nodes separated by spaces, using -1 for NULL nodes.

Example:

Input:
1
1 2 3 4 -1 5 6 -1 7 -1 -1 -1 -1 -1 -1
Output:
27 13 11 7 0 0 0

Constraints:

  • 1 <= T <= 100
  • 1 <= N <= 3000
  • -104 <= val <= 104 and val != -1

Note: The input ends when all nodes at the last level are null (-1).

AnswerBot
4mo

Convert a binary tree to a sum tree by replacing each node with the sum of its left and right subtrees, setting leaf nodes to zero.

  • Traverse the tree in postorder fashion to calculate the sum of left a...read more

Help your peers!
Select
Add answer anonymously...

Oracle Senior Application Developer interview questions & answers

A Senior Application Developer was asked 2mo agoQ. Given an m x n matrix in which each row and each column is sorted in ascending o...read more
A Senior Application Developer was asked Q. Given a binary tree, determine if it is height-balanced.
A Senior Application Developer was asked Q. What is Spring MVC?

Popular interview questions of Senior Application Developer

A Senior Application Developer was asked 2mo agoQ1. Given an m x n matrix in which each row and each column is sorted in ascending o...read more
A Senior Application Developer was asked Q2. Given a binary tree, determine if it is height-balanced.
A Senior Application Developer was asked Q3. What is Spring MVC?
Oracle Senior Application Developer 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