#C6567. Connect Levels in a Binary Tree
Connect Levels in a Binary Tree
Connect Levels in a Binary Tree
Given a binary tree represented in level order with the keyword null
indicating a missing node, your task is to connect all nodes at the same level using a next pointer. The next pointer of a node should be set to the node immediately to its right in the same level, and if there is no such node, it should be set as null
.
After connecting the nodes, each level of the tree can be viewed as a singly linked list with nodes connected from left to right. You are required to output each level of the tree as a single line in which the values of the nodes are concatenated with a ->
arrow.
For example, consider the following two binary trees:
-
Example 1
1 / \ 2 3 / \ / \ 4 5 6 7
Output:
1 2->3 4->5->6->7
-
Example 2
10 / \ 5 20 / \ 3 30
Output:
10 5->20 3->30
Note: The input is guaranteed to represent a valid binary tree in level order.
inputFormat
The input is given as a single line containing space-separated tokens representing the binary tree in level order. Each token is either an integer or the string null
, which signifies a missing node.
For example:
1 2 3 4 5 6 7
outputFormat
Output the connected node values level by level. For each level, print the node values connected by the arrow ->
without any extra labels. Each level should be printed on a new line.
For the above example, the output should be:
1 2->3 4->5->6->7## sample
1 2 3 4 5 6 7
1
2->3
4->5->6->7
</p>