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
Add answer anonymously...
Paxcom India 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