Lowest Common Ancestor of Deepest Leaves

Given the `root` of a binary tree, return the lowest common ancestor of its deepest leaves. - A node is a leaf if it has no children. - The root has depth `0`, and the children of a node at depth `d` have depth `d + 1`. - The lowest common ancestor of a set of nodes is the deepest node `A` such that every node in the set is in the subtree rooted at `A` (a node is in its own subtree). The answer is returned as a tree node; it is shown as the level-order serialization of its subtree.

30:00

Lowest Common Ancestor of Deepest Leaves
medium
Free written solution
Topics
Companies

Given the root of a binary tree, return the lowest common ancestor of its deepest leaves.

  • A node is a leaf if it has no children.
  • The root has depth 0, and the children of a node at depth d have depth d + 1.
  • The lowest common ancestor of a set of nodes is the deepest node A such that every node in the set is in the subtree rooted at A (a node is in its own subtree).

The answer is returned as a tree node; it is shown as the level-order serialization of its subtree.

Example 1:
Input: {"root":[3,5,1,6,2,0,8,null,null,7,4]}
Output: [2,7,4]
Constraints:
  • The number of nodes in the tree is in the range [1,1000][1, 1000].

  • 0≤Node.val≤10000 \leq \text{Node.val} \leq 1000

  • The values of the nodes in the tree are unique.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"root":[3,5,1,6,2,0,8,null,null,7,4]}

Start a level-by-level BFS at the root (3), remembering each node's parent so we can walk back up later.

stage

BFS down

level size

1

depth

0

d0d1d2d3351620874
current BFS level
deepest leaf
walker (climbing)
path walked
answer subtree
Variables
VariableValue
level[3]
depth0
DepthFunction Call
Stack empty
0/7