#C1389. Find Maximum Depth and Maximum Values at Each Depth
Find Maximum Depth and Maximum Values at Each Depth
Find Maximum Depth and Maximum Values at Each Depth
You are given a string representation of a binary tree. The tree is provided as a sequence of space‐separated integers, where each pair of integers represents a node: the first number of the pair is the node value and the second is the depth (or level) of that node in the tree.
The task is to determine two things for each tree:
- The maximum depth of the tree, denoted by \(D\).
- A list of maximum node values at each depth level from \(0\) to \(D\). Specifically, for each level \(i\) (where \(0 \le i \le D\)), compute \(M_i = \max\{\text{node value at depth } i\}\).
The input contains multiple trees, each tree on a new line. The end of input is denoted by a line containing only 0 (which should not be processed). For each tree, output a line containing the maximum depth and then the maximum values at each depth separated by a single space.
Example:
Input: 5 0 3 1 8 1 7 2 6 2 10 0 7 1 15 1 5 2 20 2 0 Output: 2 5 8 7 2 10 15 20
inputFormat
The input is provided on stdin and consists of multiple lines. Each non‐zero line represents a tree and contains a space‐separated list of integers. Each pair of integers correspond to a node: the first integer of the pair is the node's value and the second integer is its depth. The last line of the input will be a single 0, which signals the end of input.
For example:
5 0 3 1 8 1 7 2 6 2 10 0 7 1 15 1 5 2 20 2 0
outputFormat
For each tree (each non‐zero input line), output one line on stdout. The line should start with the maximum depth (an integer), followed by the maximum value from each depth level from 0 up to the maximum depth, each separated by a space.
For example, the output for the above input is:
2 5 8 7 2 10 15 20## sample
5 0 3 1 8 1 7 2 6 2
10 0 7 1 15 1 5 2 20 2
0
2 5 8 7
2 10 15 20
</p>