Add One Row to Tree

Given the `root` of a binary tree and two integers `val` and `depth`, add a row of nodes with value `val` at the given `depth`. The root is at depth `1`. - For every non-null node `cur` at depth `depth - 1`, create two new nodes with value `val`: one becomes `cur`'s new left child and one becomes `cur`'s new right child. - `cur`'s original left subtree becomes the left subtree of the new left node, and `cur`'s original right subtree becomes the right subtree of the new right node. - If `depth == 1`, there is no depth `0`, so create a new root with value `val` whose left subtree is the whole original tree. Return the root of the modified tree.

30:00

Add One Row to Tree
medium
Free written solution
Topics
Companies

Given the root of a binary tree and two integers val and depth, add a row of nodes with value val at the given depth. The root is at depth 1.

  • For every non-null node cur at depth depth - 1, create two new nodes with value val: one becomes cur's new left child and one becomes cur's new right child.
  • cur's original left subtree becomes the left subtree of the new left node, and cur's original right subtree becomes the right subtree of the new right node.
  • If depth == 1, there is no depth 0, so create a new root with value val whose left subtree is the whole original tree.

Return the root of the modified tree.

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]
Constraints:
  • The number of nodes in the tree is in the range [1,104][1, 10^4].

  • The depth of the tree is in the range [1,104][1, 10^4].

  • −100≤Node.val≤100-100 \leq \text{Node.val} \leq 100

  • −105≤val≤105-10^5 \leq \text{val} \leq 10^5

  • 1≤depth≤the depth of tree+11 \leq \text{depth} \leq \text{the depth of tree} + 1

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"root":[4,2,6,3,1,5],"val":1,"depth":2}

The new row goes at depth 2. Depth 1 is the root's level, which is a special case.

val = 1
depth = 2
new nodes: 0
d1d2d3new row goes here321456
level list
parent being spliced
new row node
Variables
VariableValue
val1
depth2
DepthFunction Call
Stack empty
0/4