#C5895. Level Order Traversal
Level Order Traversal
Level Order Traversal
Given a binary tree, your task is to perform a level-order traversal. In a level-order traversal, the nodes are visited level by level starting from the root, proceeding from left to right within each level.
The tree is provided in a level-order format (i.e., breadth-first order) where each token is either an integer (representing a node's value) or the string null
which indicates the absence of a node. An empty tree is represented by the token null
.
Your program should output the values of the nodes level by level. Each level's values must be printed on a separate line with the node values separated by a single space.
The level-order traversal can be mathematically described as follows:
\[ \text{result} = [\text{level}_0, \text{level}_1, \dots, \text{level}_k] \]where each level_i
is a sequence of node values collected from left to right at depth i
of the tree.
inputFormat
The input consists of a single line containing space-separated tokens representing the binary tree in level-order. Each token is either an integer or the string null
indicating a missing node. For example:
3 9 20 null null 15 7
This corresponds to the binary tree:
3 / \ 9 20 / \ 15 7
An empty tree is represented by the token null
.
outputFormat
Print the values of the nodes in level-order traversal. Each level should be printed on a new line, and the values within the same level should be separated by a space.
For example, the output for the input:
3 9 20 null null 15 7
should be:
3 9 20 15 7## sample
3 9 20 null null 15 7
3
9 20
15 7
</p>