#K74152. Subtree Sums in a Binary Tree
Subtree Sums in a Binary Tree
Subtree Sums in a Binary Tree
You are given a binary tree in level order format. Each node in the tree has an integer value. A missing node is represented by the string null
.
Your task is to compute the sum of each subtree. A subtree for a node is defined as the tree consisting of that node and all of its descendants. The result should be a list of subtree sums obtained in postorder traversal, i.e. the sums for the left subtree, then the right subtree, and finally the node itself.
The calculation for each node can be written mathematically as follows:
$$ S(node) = value(node) + S(left) + S(right) $$
If a subtree is empty, its sum is considered to be 0. If the tree is empty, output nothing.
inputFormat
The input is provided via standard input as a single line containing space-separated tokens. Each token represents a node's value in level order. Use the literal null
(without quotes) to indicate a missing node. For example, a tree with nodes [1, 2, 3, 4, 5, 6, 7] is given as:
1 2 3 4 5 6 7
An empty tree is represented by an empty input.
outputFormat
Print the subtree sums (as computed in postorder) as a sequence of integers separated by a single space via standard output. If the tree is empty, output nothing.
## sample5 3 8 1 4 7 10
1 4 8 7 10 25 38