Add One Row to Tree (LeetCode 623): Solution and Explanation

Medium
Tree
Depth First Search
Breadth First Search
Binary Tree

Insert a row of nodes with value val at a given depth of a binary tree. The old subtrees at that spot slide one level down, left under the new left node and right under the new right node.

Intuition

Inserting a row at depth d only changes the nodes directly above it, the ones at depth d - 1. Everything else keeps its shape, it just ends up one level lower if it was below the new row.

For one such parent the change is a local splice. Its old left child moves under a new left node, and its old right child moves under a new right node. The sides never cross over.

So the job is: reach all nodes at depth d - 1, which a level-by-level walk does naturally, and splice each one. Depth 1 has no parent level, so there the new node simply becomes the root with the old tree on its left.

Approach: Level walk, then splice

  1. If depth == 1, return a new node val whose left child is root.
  2. Set level = [root].
  3. Repeat depth - 2 times: replace level with the non-null children of its nodes, left to right.
  4. For every node in level: node.left = TreeNode(val, node.left, None) and node.right = TreeNode(val, None, node.right).
  5. Return root.

Step-by-step example

root = [4,2,6,3,1,5], val = 1, depth = 2
  1. depth is 2, not 1, so the root stays.
  2. level = [4]. depth - 2 = 0, so no walking is needed: 4 is the only node at depth 1.
  3. Splice under 4: a new left node 1 adopts the old left subtree rooted at 2, and a new right node 1 adopts the old right subtree rooted at 6.
  4. Return 4. In level order the tree is [4,1,1,2,null,null,6,3,1,5].

Code: Python, Java, C++

1class Solution:
2    def addOneRow(self, root: Optional[TreeNode], val: int, depth: int) -> Optional[TreeNode]:
3        if depth == 1:
4            return TreeNode(val, root, None)
5        level = [root]
6        for _ in range(depth - 2):
7            level = [kid for node in level for kid in (node.left, node.right) if kid]
8        for node in level:
9            node.left = TreeNode(val, node.left, None)
10            node.right = TreeNode(val, None, node.right)
11        return root
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

The walk visits each node above the new row at most once, and the splice is constant work per parent.

Space

O(w)

The level list holds one level at a time, at most the width w of the tree.

Other approaches

DFS with a depth counter (time O(n), space O(h))

Recurse with the current depth. When it equals depth - 1, splice and stop descending. Same result and same time, with O(h) recursion stack instead of a level list.

Rebuild from the level-order array (time O(n), space O(n))

Serialize the tree, insert the new values in the right positions of the array and rebuild. Possible but much harder to get right because null placeholders shift.

Common mistakes

  • Forgetting the depth == 1 case, where the answer has a new root instead of a changed old root.
  • Putting the old right subtree under the new left node, or the reverse. The left subtree stays on the left and the right on the right.
  • Walking depth - 1 levels instead of depth - 2: level starts at depth 1, so it needs depth - 2 steps to reach depth - 1.
  • Inserting only where children exist. Every node at depth - 1 gets both new children, even a leaf.

Frequently asked questions

What happens when depth is one more than the tree height?

The nodes at depth - 1 are the deepest nodes, which are leaves. Each of them gets two new leaf children, so the new row becomes the bottom of the tree.

Why does depth == 1 put the old tree on the left?

The problem defines it that way: the new root takes the original tree as its left subtree, matching the rule that old left subtrees go under new left nodes.

Does the order of nodes in the level list matter?

Not for correctness. Every node at depth - 1 is spliced independently, so any order of visiting them gives the same tree.