Populating Next Right Pointers in Each Node

Medium

Description

Given a perfect binary tree, 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.

Examples

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

Connect nodes at the same level.

Input:root = [1]
Output:[1]
Explanation:

Edge case with a single-element array.

Input:root = []
Output:[]
Explanation:

Edge case with an empty tree. When there are no nodes, the output is also empty since there are no next pointers to populate.

Constraints

  • 0 ≤ number of nodes ≤ 2¹² - 1
  • -1000 ≤ Node.val ≤ 1000

Ready to solve this problem?

Practice solo or challenge other developers in a real-time coding battle!