Skip to content

Practice Add One Row to Tree

Read the task, work through the examples, and check your approach against the constraints. Use the original LeetCode task for coding and submissions.

Medium#623
LeetCode Problem

Add One Row to Tree

Problem Statement

Given root, val, and depth, where the root has depth 1, insert a row of nodes valued val. For each existing node at depth - 1, create new left and right children. Attach its former left subtree as the new left child’s left subtree and its former right subtree as the new right child’s right subtree. When depth is 1, create a new root with val and attach the entire original tree as its left subtree. Return the resulting root.

Source: Add One Row to Tree on LeetCode. Use the original task for its coding environment and submissions.

Examples

# 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]

Constraints

The number of nodes in the tree is in the range [1, 10^4].
The depth of the tree is in the range [1, 10^4].
-100 <= Node.val <= 100
-10^5 <= val <= 10^5
1 <= depth <= the depth of tree + 1

Related LeetCode Problems

Practice more problems similar to Add One Row to Tree.

Review your practice with PhantomCodeAI

After trying the problem yourself, use the app to discuss your approach, complexity, and edge cases.