Insert a new row of nodes with a given value at a specified depth in a binary tree.
You are given the root of a binary tree, an integer value val, and an integer depth depth.
Add a new row of nodes with value val at the given depth.
depth = 1, create a new root node with value val.depth - 1, insert two new nodes below it:
All other existing structure should remain unchanged.
Return the root of the modified tree.
valdepth1 <= depth <= $10^{4}$ is typical for this kind of tree problemExample 1
Input
root = [4,2,6,3,1,5], val = 1, depth = 2
Output
[4,1,1,2,null,null,6,3,1,5]
Explanation
A new row of value 1 is inserted at depth 2. The original children of the root are reattached beneath the new nodes.
Example 2
Input
root = [4,2,null,3,1], val = 1, depth = 3
Output
[4,2,null,1,1,null,null,3,null,null,1]
Explanation
Nodes are inserted below every node at depth 2, and the old subtrees are preserved under the newly created nodes.
Example 3
Input
root = [], val = 7, depth = 1
Output
[7]
Explanation
When the tree is empty and depth is 1, the result is a single new root node.
Premium problem context
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.