Populating Next Right Pointers in Each Node II

You are given a binary tree whose nodes have val, left, right and next fields. Populate each next pointer to point to the next node to its right on the same level. If there is no such node, next stays NULL. Initially every next pointer is NULL. Unlike part I, the tree is not necessarily perfect: any child may be missing. The output lists each level by following next pointers, with # marking the end of a level.

30:00

Populating Next Right Pointers in Each Node II
medium
Free written solution
Topics
Companies

You are given a binary tree whose nodes have val, left, right and next fields. Populate each next pointer to point to the next node to its right on the same level. If there is no such node, next stays NULL. Initially every next pointer is NULL. Unlike part I, the tree is not necessarily perfect: any child may be missing. The output lists each level by following next pointers, with # marking the end of a level.

Example 1:
Input: {"root":[1,2,3,4,5,null,7]}
Output: [1,#,2,3,#,4,5,7,#]
Constraints:
  • The number of nodes in the tree is in the range [0,6000][0, 6000].

  • −100≤Node.val≤100-100 \leq \text{Node.val} \leq 100

  • Follow-up: use only constant extra space (the recursion stack does not count).

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"root":[1,2,3,4,5,null,7]}

level_start = root (1). Idea: walk each level left to right through next pointers that are already set, and thread the level below as we go. No queue needed.

tree with next pointers (6 nodes)

● cur

● prev (tail below)

● child

→ next

1start↓23457

levels read through next

L0

1

→ null #

L1

2

1 not linked yet

L2

4

2 not linked yet

Variables
VariableValue
curnull
prevnull
levelStart1
DepthFunction Call
Stack empty
0/20