Medium

Quiz

#623 Add One Row to Tree

APPROACH

Given the root of a binary tree and integers val and depth (root is at depth 1), insert a new row of nodes with value val at the specified depth. For each existing node at depth depth - 1, add new left and right children with value val; the original left subtree becomes the new left child's left subtree, and the original right subtree becomes the new right child's right subtree. If depth == 1, the new node becomes the root with the original tree as its left subtree.

Example 1:

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

Example 2:

Input: root = [4,2,null,3,1], val = 1, depth = 3
Output: [4,2,null,1,1,3,null,null,1]
1 of 4
1:00

What is the optimal approach for this problem?