#C8335. Binary Tree Level Order Traversal
Binary Tree Level Order Traversal
Binary Tree Level Order Traversal
You are given the level order representation of a binary tree as a single line of input. The tree nodes are given in a comma-separated format, where each value represents a node of the tree in level order. If a node does not exist, it is represented by the string null
(case insensitive).
Your task is to perform a level order traversal (also known as breadth-first search) of the binary tree and output the values of the nodes level by level.
Note: Each level should be printed on a new line, and the node values within each level should be space-separated.
Example:
Input: 3,9,20,null,null,15,7 The tree corresponds to: 3 / \ 9 20 / \ 15 7 Output: 3 9 20 15 7
Hint: You may use a queue to help traverse the tree level by level.
For more details, recall that the binary tree structure is defined as follows:
$$\textbf{TreeNode}: \quad \{ val,\, left,\, right \} $$inputFormat
The input is given in a single line as a comma-separated list of values representing the binary tree in level order. Each value is either an integer or the string null
(indicating a missing node). For example:
3,9,20,null,null,15,7
outputFormat
Output the level order traversal of the tree. Each level's nodes should be printed on a new line, and the node values within the same level should be separated by a space. No extra spaces or blank lines should be printed.
## sample3,9,20,null,null,15,7
3
9 20
15 7
</p>