KatInterview

623. Add One Row to Tree

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to insert a new row of nodes with a given value val at a specific depth in a binary tree. The root is at depth 1. For each node at depth - 1, we need to insert two new nodes with value val as its new left and right children. The original left and right subtrees of the node at depth - 1 should be reattached to the new left and right children, respectively. A special case is when depth is 1, where a new root is created, and the original tree becomes its left subtree.

Solution

Add One Row to Tree in Python

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
from collections import deque

class Solution:
    def addOneRow(self, root: Optional[TreeNode], val: int, depth: int) -> Optional[TreeNode]:
        # According to constraints, root is not None, but this check is for robustness.
        if not root:
            return None

        # Handle the edge case where depth is 1.
        if depth == 1:
            return TreeNode(val, root, None)

        # Use a queue for BFS to find nodes at depth - 1.
        queue = deque([root])
        current_depth = 1
        
        # Traverse to the level just before the target depth.
        # We want to stop at depth - 1, so the loop goes up to depth - 2.
        while current_depth < depth - 1:
            level_size = len(queue)
            for _ in range(level_size):
                node = queue.popleft()
                if node.left:
                    queue.append(node.left)
                if node.right:
                    queue.append(node.right)
            current_depth += 1
            
        # Now, the queue contains all nodes at depth - 1.
        # Iterate through these nodes and insert the new row.
        while queue:
            parent = queue.popleft()
            
            # Store original children.
            temp_left = parent.left
            temp_right = parent.right
            
            # Create new nodes and insert them.
            parent.left = TreeNode(val, temp_left, None)
            parent.right = TreeNode(val, None, temp_right)
            
        return root

Add One Row to Tree in Java

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
import java.util.LinkedList;
import java.util.Queue;

class Solution {
    public TreeNode addOneRow(TreeNode root, int val, int depth) {
        // According to constraints, root is not null, but this check is for robustness.
        if (root == null) {
            return null;
        }

        // Handle the edge case where depth is 1.
        if (depth == 1) {
            TreeNode newRoot = new TreeNode(val);
            newRoot.left = root;
            return newRoot;
        }

        // Use a queue for BFS to find nodes at depth - 1.
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        int currentDepth = 1;

        // Traverse to the level just before the target depth.
        while (currentDepth < depth - 1) {
            int levelSize = queue.size();
            for (int i = 0; i < levelSize; i++) {
                TreeNode node = queue.poll();
                if (node.left != null) {
                    queue.offer(node.left);
                }
                if (node.right != null) {
                    queue.offer(node.right);
                }
            }
            currentDepth++;
        }

        // Now, the queue contains all nodes at depth - 1.
        // Iterate through these nodes and insert the new row.
        while (!queue.isEmpty()) {
            TreeNode parent = queue.poll();
            
            // Store original children.
            TreeNode tempLeft = parent.left;
            TreeNode tempRight = parent.right;

            // Create new nodes and insert them.
            parent.left = new TreeNode(val, tempLeft, null);
            parent.right = new TreeNode(val, null, tempRight);
        }

        return root;
    }
}

Add One Row to Tree in C++

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
#include <queue>

class Solution {
public:
    TreeNode* addOneRow(TreeNode* root, int val, int depth) {
        // According to constraints, root is not null, but this check is for robustness.
        if (!root) {
            return nullptr;
        }

        // Handle the edge case where depth is 1.
        if (depth == 1) {
            TreeNode* newRoot = new TreeNode(val);
            newRoot->left = root;
            return newRoot;
        }

        // Use a queue for BFS to find nodes at depth - 1.
        std::queue<TreeNode*> q;
        q.push(root);
        int currentDepth = 1;

        // Traverse to the level just before the target depth.
        while (currentDepth < depth - 1) {
            int levelSize = q.size();
            for (int i = 0; i < levelSize; ++i) {
                TreeNode* node = q.front();
                q.pop();
                if (node->left) {
                    q.push(node->left);
                }
                if (node->right) {
                    q.push(node->right);
                }
            }
            currentDepth++;
        }

        // Now, the queue contains all nodes at depth - 1.
        // Iterate through these nodes and insert the new row.
        while (!q.empty()) {
            TreeNode* parent = q.front();
            q.pop();

            // Store original children.
            TreeNode* tempLeft = parent->left;
            TreeNode* tempRight = parent->right;

            // Create new nodes and insert them.
            parent->left = new TreeNode(val, tempLeft, nullptr);
            parent->right = new TreeNode(val, nullptr, tempRight);
        }

        return root;
    }
};

Add One Row to Tree in TypeScript

/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

function addOneRow(root: TreeNode | null, val: number, depth: number): TreeNode | null {
    // According to constraints, root is not null, but this check is for robustness.
    if (!root) {
        return null;
    }
    
    // Handle the edge case where depth is 1.
    if (depth === 1) {
        return new TreeNode(val, root, null);
    }

    // Use a queue for BFS to find nodes at depth - 1.
    const queue: TreeNode[] = [root];
    let currentDepth = 1;

    // Traverse to the level just before the target depth.
    while (currentDepth < depth - 1) {
        const levelSize = queue.length;
        for (let i = 0; i < levelSize; i++) {
            const node = queue.shift()!;
            if (node.left) {
                queue.push(node.left);
            }
            if (node.right) {
                queue.push(node.right);
            }
        }
        currentDepth++;
    }

    // Now, the queue contains all nodes at depth - 1.
    // Iterate through these nodes and insert the new row.
    while (queue.length > 0) {
        const parent = queue.shift()!;
        
        const tempLeft = parent.left;
        const tempRight = parent.right;
        
        parent.left = new TreeNode(val, tempLeft, null);
        parent.right = new TreeNode(val, null, tempRight);
    }

    return root;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.