Populating Next Right Pointers in Each Node

IF
AlgoAxiomStaff Engineers
JSTS
Medium20 mins

You are given a perfect binary tree where all leaves are on the same level, and every parent has two children. The tree node has the following definition:

`

function Node(val, left, right, next) {

this.val = val;

this.left = left;

this.right = right;

this.next = next;

}

`

Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to null.

Initially, all next pointers are set to null.

Examples

Example 1:

1234567

Input: root = [1, 2, 3, 4, 5, 6, 7]

Output: [1, #, 2, 3, #, 4, 5, 6, 7, #]

Explanation: The # symbols represent the end of each level (where next is null). Node 2's next points to 3, node 4's next points to 5, 5's next points to 6, and 6's next points to 7.

Example 2:

Input: root = []

Output: []

Example 3:

123

Input: root = [1, 2, 3]

Output: [1, #, 2, 3, #]

Constraints

  • The number of nodes in the tree is in the range [0, 4096]
  • -1000 <= Node.val <= 1000
  • The tree is a perfect binary tree
Source: Tree Breadth-First Search pattern — AlgoAxiom
JavaScript
Test Case 1
root = [1, 2, 3]
Test Case 2
root = [1, 2, 3, 4, 5]
Idle