DDSA Solutions

1123. Lowest Common Ancestor of Deepest Leaves

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

Intuition

Find LCA of all deepest leaves. Same as problem 865: DFS returning (depth, lca_of_deepest).

Algorithm

  1. 1DFS returns (max_depth, lca_node).
  2. 2If left.depth == right.depth: return (depth+1, current).
  3. 3Return from deeper side.

Common Pitfalls

  • If deepest leaves all in one subtree, LCA is not the root.
1123.cs
C#
// Approach: Post-order DFS returning (lca, depth); when left and right depths are equal the current node is the LCA of the deepest leaves.
// Time: O(n) Space: O(n)

public class TreeNode(TreeNode root)
    {
        return Dfs(root).Lca;
    }

    private record T(TreeNode Lca, int Depth);

    private T Dfs(TreeNode root)
    {
        if (root == null)
            return new T(null, 0);

        T left = Dfs(root.left);
        T right = Dfs(root.right);

        if (left.Depth > right.Depth)
            return new T(left.Lca, left.Depth + 1);

        if (left.Depth < right.Depth)
            return new T(right.Lca, right.Depth + 1);

        return new T(root, left.Depth + 1);
    }
}
Advertisement
Was this solution helpful?