#623
Add One Row to Tree
specialist · 650 · lc medium +30 · verified · 64.1% accepted · 3,674 likes · top 67%
Description
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]
Code
1
2
3
4
5
6
7
8
9