Problem
As leetcode problem 1123:
Given the root
of a binary tree, return the lowest common ancestor of its deepest leaves.
Recall that:
- The node of a binary tree is a leaf if and only if it has no children
- The depth of the root of the tree is
0
. if the depth of a node isd
, the depth of each of its children isd + 1
. - The lowest common ancestor of a set
S
of nodes, is the nodeA
with the largest depth such that every node inS
is in the subtree with rootA
.
OR
As problem 865:
Given the root
of a binary tree, the depth of each node is the shortest distance to the root.
Return the smallest subtree such that it contains all the deepest nodes in the original tree.
A node is called the deepest if it has the largest depth possible among any node in the entire tree.
The subtree of a node is a tree consisting of that node, plus the set of all descendants of that node.
Signature:
|
|
Examples
Example 1:
graph TD D(3) D --- F(5) D --- B(1) F --- G(6) F --- A(2):::orangeYellow B --- H(0) B --- C(8) A --- E(7):::blueShade A --- I(4):::blueShade classDef orangeYellow fill:#FFD700,stroke:#000,stroke-width:1px,color:#000; classDef blueShade fill:#1E90FF,stroke:#000,stroke-width:1px,color:#fff;
|
|
Example 2:
|
|
Example 3:
|
|
Constraints:
- The number of nodes in the tree will be in the range
[1, 1000]
. 0 <= Node.val <= 1000
- The values of the nodes in the tree are unique.
Note: This question is the same as 865: https://leetcode.com/problems/smallest-subtree-with-all-the-deepest-nodes/
Solution
Method 1 - Postorder Traversal
To solve this, we can perform a bottom-up recursive traversal (post-order traversal), where for each node:
- Compute the depth of its left and right subtrees.
- If the depths are equal, the current node is the lowest common ancestor of the deepest leaves in its subtree.
- If one subtree is deeper, propagate the LCA and depth of that subtree upwards.
This ensures that when recursion reaches the root, we have obtained the LCA of the deepest leaves in the entire tree.
Steps
- Use a helper function that returns both the depth and the LCA of the subtree rooted at the current node.
- Perform post-order traversal (visit left and right subtree first, then decide the LCA for the current node).
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n)
. Traversal of the tree involves visiting all nodes once:O(n)
. - 🧺 Space complexity:
O(h)
. Recursive function stack requires space proportional to the height of the tree:O(h)
, whereh
is the height of the tree. In the worst case, for a skewed tree,h = n
.