[ OK ]384da830-5924-4fd7-824a-2629464fa0f6 — full content available
[ INFO ]category: Coding difficulty: unknown freq: first seen: 2026-03-13
[UNKNOWN][CODING]
$catproblem.md
The "Rewrite Tree With Subtree Sums" interview question, often associated with companies like xAI and Snowflake, requires transforming a binary tree into a "Sum Tree" where each node's value is replaced by the sum of all elements in its left and right subtrees.
Problem Statement
Given the root of a binary tree, modify the tree in-place so that every node contains the sum of all nodes in its original left and right subtrees. Naukri.com +1
Key Constraints & Definitions:
Leaf Nodes: The value of a leaf node becomes 000 because it has no subtrees.
Subtree Sum: For any node, the new value is 𝑆𝑢𝑚(Left Subtree)+𝑆𝑢𝑚(Right Subtree), where these sums refer to the original values of the nodes in those subtrees.
Return Value: Typically, the function modifies the tree in-place and may return the total sum of the original tree to assist with recursive calculations. YouTube +2
Example
Input Tree:
`text
10
/
-2 6
/ \ /
8 -4 7 5
`
Output Tree (after rewriting):
`text
20 (8-4 + 7+5)
/
4 12 (7+5)
/ \ /
0 0 0 0
`
Recommended Approach
The most efficient way to solve this is using a post-order traversal (Left, Right, Root). Naukri.com +1
Base Case: If the node is null, return 000.
Recursively calculate the sum of the left subtree.
Recursively calculate the sum of the right subtree.
Recursively calculate the sum of the left subtree.
Recursively calculate the sum of the right subtree.
Store the node's original value (to return to the parent).
Set the node's new value to leftSum + rightSum.
Store the node's original value (to return to the parent).
Set the node's new value to leftSum + rightSum.
Return: Return the oldValue + leftSum + rightSum so the parent can calculate its own subtree sum. Naukri.com +1
Would you like to see a Python or C++ implementation of this recursive solution?