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.
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].
−100≤Node.val≤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.