The Add One Row to Tree coding problem asks you to insert a full row of nodes with a specific value at a given depth d in a binary tree. For every existing node at depth d-1, you create two new nodes. The old left child becomes the left child of the new left node, and the old right child becomes the right child of the new right node.
This is a standard Tree traversal question used by Microsoft and Google. it tests your ability to manipulate pointers and maintain tree structure while navigating to a specific level. It requires precision in handling child assignments to prevent losing entire subtrees.
This can be solved using either the Breadth-First Search (BFS) or Depth-First Search (DFS) interview pattern.
d-1.Target depth: 2, Value: 1. Original tree:
4
/ \
2 6
At depth 1 (node 4), we add the new row:
4
/ \
1 1
/ \
2 6
The original 2 is now the left child of the new 1, and the original 6 is the right child of the other new 1.
d-1 nodes are deleted or orphaned.d instead of depth d-1 to perform the insertion.In tree problems involving "rows" or "levels," BFS is often more intuitive. However, DFS is usually more concise to code. Practice both to see which one you can implement faster without bugs.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Find Largest Value in Each Tree Row | Medium | Solve | |
| Find Bottom Left Tree Value | Medium | Solve | |
| Maximum Width of Binary Tree | Medium | Solve | |
| Count Good Nodes in Binary Tree | Medium | Solve | |
| Maximum Level Sum of a Binary Tree | Medium | Solve |