← 返回 snowflake 的题目列表Rewrite Tree with Subtree Sums
类型:online_judge
Problem: Rewrite Tree with Subtree Sums
Given a binary tree where each node contains an integer value, rewrite every node's value to be the sum of all original values in the subtree rooted at that node.
For every node node:
node.val = sum(original values of all nodes in node's subtree)
Return the rewritten tree.
Input Format
The first line contains an integer n, the length of the level-order array.
The second line contains n tokens representing the binary tree in level order.
An integer represents a node value.
null represents an empty node.
Output Format
Print the rewritten tree in level-order traversal, separated by spaces, with trailing null values removed.
Constraints
0 <= n <= 10^5
Node value range: -10^9 <= val <= 10^9
The input is guaranteed to represent a valid binary tree.
Example 1
Input:
7
1 2 3 4 5 6 7
Output:
28 11 16 4 5 6 7
Explanation:
The root becomes 1+2+3+4+5+6+7 = 28.
Node 2 becomes 2+4+5 = 11.
Node 3 becomes 3+6+7 = 16.
Example 2
Input:
7
5 3 8 null 4 null 10
Output:
30 7 18 null 4 null 10
Example
Input
7
1 2 3 4 5 6 7
Output
28 11 16 4 5 6 7