DDSA Solutions

623. Add One Row to Tree

Time: O(n)
Space: O(n)
Advertisement

Intuition

BFS or DFS to find all nodes at depth d-1, then insert new nodes with value v between those nodes and their children.

Algorithm

  1. 1Special case: if d==1, create new root with val=v, left=old root.
  2. 2BFS to level d-1. For each node at that level:
  3. 3Create new_left(v) with new_left.left=node.left, attach to node.left.
  4. 4Create new_right(v) with new_right.right=node.right, attach to node.right.

Common Pitfalls

  • Handle d=1 separately. Remember new_left.left=old node.left and new_right.right=old node.right.
623.cs
C#
// Approach: BFS to the (depth-1)th level; insert a new node with the given
// value as the left/right child of every node at that level.
// Time: O(n) Space: O(n)

public class TreeNode
{
    public int val;
    public TreeNode left;
    public TreeNode right;
    public TreeNode(int val = 0, TreeNode left = null, TreeNode right = null)
    {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

public class Solution
{
    public TreeNode AddOneRow(TreeNode root, int val, int depth)
    {
        if (depth == 1)
        {
            TreeNode newNode = new TreeNode(val);
            newNode.left = root;
            return newNode;
        }

        int d = 0;
        var q = new Queue<TreeNode>();
        q.Enqueue(root);

        while (q.Count > 0)
        {
            d++;
            int cnt = q.Count;
            for (int i = 0; i < cnt; i++)
            {
                TreeNode node = q.Dequeue();
                if (node.left != null)
                    q.Enqueue(node.left);

                if (node.right != null)
                    q.Enqueue(node.right);

                if (d == depth - 1)
                {
                    TreeNode cachedLeft = node.left;
                    TreeNode cachedRight = node.right;
                    node.left = new TreeNode(val);
                    node.right = new TreeNode(val);
                    node.left.left = cachedLeft;
                    node.right.right = cachedRight;
                }
            }

            if (d == depth - 1)
                break;
        }

        return root;
    }
}
Advertisement
Was this solution helpful?