Convert Binary tree into Sum tree
Pattern: Tree DP basics
Replace each node's value with the sum of all values in its left and right subtrees (its own old value not included); leaves become 0. One post-order pass that returns each subtree's old total does it.
No verified practice link yet. The guide below states the problem in full, so you can still solve it here.
The problem
Change the tree in place so that each node holds the sum of the original values below it (in both subtrees); leaves
become 0. The function returns nothing; the tests print the tree. The catalogue has no practice link for this one. Trees in the examples are written in level order, with null for a missing child, as on LeetCode.
Think first
- What should a leaf become?
- What does a node need from its children?
- Why must the old value be returned, not the new one?
Hints
Brute force, and why it fails
Compute each subtree's sum separately for every node: O(n²).
The key insight
A post-order pass gets both children's original totals before overwriting the node, so each node is done in O(1).
Dry run
Tree [10, -2, 6, 8, -4, 7, 5]. Leaves 8, -4, 7, 5 become 0 and report their old values.
The plan
convert(n): if null: 0
old = n.val
n.val = convert(left) + convert(right)
return n.val + old
Complexity
- Time
O(n)- Space
O(h)
One post-order pass.
Edge cases
- Empty tree.
- One node: becomes 0.
- Negative values.
I've built my logic, show the code
Java
class Solution {
public void toSumTree(TreeNode root) {
convert(root);
}
private int convert(TreeNode n) { // returns the old sum of this subtree
if (n == null) return 0;
int old = n.val;
n.val = convert(n.left) + convert(n.right); // the sum of everything below
return n.val + old;
}
}C++
class Solution {
public:
void toSumTree(TreeNode* root) {
convert(root);
}
int convert(TreeNode* n) { // returns the old sum of this subtree
if (n == NULL) return 0;
int old = n->val;
n->val = convert(n->left) + convert(n->right); // the sum of everything below
return n->val + old;
}
};Python
class Solution:
def toSumTree(self, root) -> None:
def convert(n) -> int: # returns the old sum of this subtree
if n is None:
return 0
old = n.val
n.val = convert(n.left) + convert(n.right) # the sum of everything below
return n.val + old
convert(root)Common mistakes
- Returning the new value, which loses the node's own old value.
- Overwriting the value before using it.