oneby7

Binary Trees Breadth first: level by level

376. Populating Next Right Pointers in Each Node

Medium

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

1863-2-59

Input: root = [3, 8, -5, 1, 6, -2, 9]

Output: [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 = []

Output: []

Explanation: The tree has no nodes, so there is nothing to link.

Example 3

−10⁹

Input: root = [-1000000000]

Output: [-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.

root = [6, -2, 9, 0, 4, 7, 1]

Constraints

  • 0 ≤ number of nodes ≤ 217 − 1
  • -109 ≤ Node.val ≤ 109
  • The tree is perfect, with at most 17 levels. A perfect tree with h levels has 2h − 1 nodes.

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.