Populating Next Right Pointers in Each Node II

Medium#117tree nodes

Every node of a binary tree has one more pointer, next, which starts as none. Point each node's next at the node to its right on the same level; the rightmost node of a level keeps none. The tree need not be full, so a level may have gaps. Return the root. Our example: the tree [6, 2, 9, 1, 4, none, 8] in level order — after the run the levels read 6 → none; 2 → 9 → none; 1 → 4 → 8 → none.

input
root: a binary tree, written level by level as on LeetCode (null where a child is missing); each node also has a pointer next, null for now.
returns
root, with each node’s next set to the node to its right on the same level, and null for the last node of a level. The tests print it as LeetCode does: each level by next, then #.
constraints
  • root is a tree in level order
  • 0 ≤ the number of nodes ≤ 6000
  • −100 ≤ Node.val ≤ 100
our 12 tests keep to them
examples
Open a test in the tests panel: it shows the input and the expected answer.
/**
 * // Definition for a _Node.
 * function _Node(val, left, right, next) {
 *    this.val = val === undefined ? null : val;
 *    this.left = left === undefined ? null : left;
 *    this.right = right === undefined ? null : right;
 *    this.next = next === undefined ? null : next;
 * };
 */

/**
 * @param {_Node} root
 * @return {_Node}
 */
function connect(root) {

}
Ctrl ↵
format
reset

saved in this browser

12 tests · limit 3 s

Stuck?

See the solution run step by step on our example, then why it works and its complexity.

Watch the walkthrough →

Next: more breadth-first search (bfs) problems

Pattern “Breadth-first search (BFS)” →

The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.