Sum Tree Conversion

Convert a given binary tree into its sum tree. In a sum tree, every node's value is replaced with the sum of its immediate children's values. Leaf nodes are set to 0. Finally, return the preorder traversal of the sum tree.

Input:

Elements of the input are given in level order traversal. Each node value is given on a new line. Use -1 to represent null nodes.

Output:

Output the preorder traversal of the converted sum tree.

Example:

Input:
1
2
3
4
-1
5
6
-1
7
-1
-1
-1
-1
-1
-1
Explanation:

The binary tree given in the input can be organized based on the level order as depicted in the image provided. The conversion involves changing each node's value except leaves to the sum of its children and setting the leaves to 0. Once the tree is converted, return its preorder traversal.

Constraints:

  • 0 <= Number of nodes <= 10^7
  • 0 <= Value of node <= 10^8
Be the first one to answer
Select
Add answer anonymously...
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