Description

Given the root of a binary tree, an integer val, and an integer depth, add a row of nodes with value val at the given depth d. Original subtrees become children of the new row.

Examples

Input:root = [4,2,6,3,1,5], val = 1, depth = 2
Output:[4,1,1,2,null,null,6,3,1,5]
Explanation:

Add row at depth 2.

Input:root = [1], val = 1, depth = 2
Output:[1]
Explanation:

Edge case with a single-element array.

Input:root = [1,2,3,4,5], val = 9, depth = 1
Output:[9,1,null,2,3,4,5]
Explanation:

When depth = 1, replacing the root with a new node containing val = 9, and the original tree becomes the left child of this new root.

Constraints

  • 1 ≤ nodes ≤ 10⁴

Ready to solve this problem?

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