#C2946. Connect Next Right Pointers in Binary Tree

    ID: 46318 Type: Default 1000ms 256MiB

Connect Next Right Pointers in Binary Tree

Connect Next Right Pointers in Binary Tree

Given a binary tree, write a program to connect each node's next pointer to its right adjacent node in the same level. If there is no right adjacent node, set the next pointer to NULL. The connecting should be done in-place.

The binary tree is provided in level order format as a single line of input where each value is separated by a space, and missing children are represented by the string null. After connecting the nodes, output the tree level by level. For every level, output the sequence of node values followed by an arrow (->), ending with a '#' to denote the end of the level. For example, a level with nodes 2 and 3 should be printed as:

2->3->#

The classic solution uses a level-by-level traversal. One can prove that the time complexity is \(O(n)\) and the extra space complexity (not counting the output) is \(O(1)\) when the tree is perfect, and \(O(n)\) in the worst-case scenario.

inputFormat

The input is a single line representing the level order traversal of the binary tree. Each node's value is separated by a space. The string null represents a missing (empty) child.

Examples:

  • 1 2 3 4 5 null 7
  • 10 5 15 2 6 12 20
  • 1

outputFormat

For each level of the binary tree, output a single line containing the node values connected by '->', and end each level with a '#' symbol to denote the end.

Examples:

  • For input 1 2 3 4 5 null 7, the output should be:
1->#
2->3->#
4->5->7->#
## sample
1 2 3 4 5 null 7
1->#

2->3-># 4->5->7->#

</p>