Binary Trees Breadth first: level by level
376. Populating Next Right Pointers in Each Node
You are given root, the root of a perfect binary tree. In a perfect binary tree every level is full:
every node has two children except the leaves, and all the leaves are on the bottom level.
Besides val, left and right, each node has a pointer next, and at the start every next is null.
Point each node's next at the node to its right on the same level. The last node of a level has no node to
its right, so its next stays null. Change only next, and return root.
The examples write a tree level by level, from left to right, so root = [5,8,3] is the root 5 with a left
child 8 and a right child 3. The output shows what your next pointers link. For each level, from the top
down, it starts at the leftmost node, writes the value of every node it reaches by following next until
next is null, and then writes # to end the level.
Example 1
Input: root = [3, 8, -5, 1, 6, -2, 9]
[3,#,8,-5,#,1,6,-2,9,#]Explanation: On the second level 8 points to −5. On the third, 1 points to 6, 6 to −2 and −2 to 9, even though 6 and
−2 have different parents. The last node of each level, 3, −5 and 9, keeps a null next.
Example 2
Input: root = []
[]Explanation: The tree has no nodes, so there is nothing to link.
Example 3
Input: root = [-1000000000]
[-1000000000,#]Explanation: The root is alone on its level, so its next stays null.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
0 ≤ number of nodes ≤ 217 − 1-109 ≤ Node.val ≤ 109- The tree is perfect, with at most 17 levels. A perfect tree with
hlevels has2h − 1nodes.
Clarifying questions
What you would ask an interviewer before writing any code.