1668. Descendant Sum Tree

A company is arranged as a binary tree root, where each employee node holds the monthly bonus val they earn (it may be negative for a penalty). The head office wants every node to instead show the total of the original bonuses of all employees below it, meaning every node in its left and right subtrees but not the node itself. A node with no children therefore becomes 0.

Rewrite the values in place; nothing is returned and the root remains the same node. Every sum must use the original values, not values already rewritten lower down, so a post-order pass that hands each subtree's original total up to its parent works well. Expected: O(n) time and O(n) space.

Example 1

Input:
root = [10,-4,6,3,null,2,1]
Output:
[8,3,3,0,null,0,0]
Explanation:

The rewritten tree is [8, 3, 3, 0, null, 0, 0].

Example 2

Input:
root = [1,2,3]
Output:
[5,0,0]
Explanation:

The rewritten tree is [5, 0, 0].

Constraints

1 ≤ nodes ≤ 500; -1000 ≤ Node.val ≤ 1000

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Graded
Your answer is read from root after your method returns.
Time per case
Python 1,200 msC++ 300 msJava 600 msJavaScript 600 msTypeScript 600 ms

Expected complexity

Time
O(n)
Space
O(n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…