Populating Next Right Pointers in Each Node II

IF
AlgoAxiomStaff Engineers
JSTS
Medium20 mins

Given a binary tree (not necessarily perfect), 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.

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;

}

`

Initially, all next pointers are set to null.

Examples

Example 1:

123457

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

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

Explanation: Node 2's next points to 3. Node 4's next points to 5, and 5's next points to 7 (skipping the missing node).

Example 2:

Input: root = []

Output: []

Example 3:

1234578

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

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

Constraints

  • The number of nodes in the tree is in the range [0, 6000]
  • -100 <= Node.val <= 100
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