Ctrl K

Smallest Cover of the Bottom Row

Medium
You are given the root of a binary tree. A node's depth is the number of edges between it and the root. The bottom row of the tree is the set of all nodes with the greatest depth. The subtree of a node is that node together with all of its descendants. Find the subtree with the fewest nodes that contains the entire bottom row and return its root; the whole subtree is checked.
Example 1
root=tree_node([7, 2, 9, 4, 6, None, 1, None, None, 3, 8]) → [6, 3, 8]

The bottom row (depth 3) is nodes 3 and 8, both children of node 6. The smallest subtree holding both of them is the one rooted at 6.

Example 2
root=tree_node([5, 0, 11, 12, None, None, 13]) → [5, 0, 11, 12, None, None, 13]

The bottom row is 12 (under 0) and 13 (under 11). They only come together at the root 5, so the answer is the whole tree.

Example 3
root=tree_node([40, None, 30, 20]) → [20]

The bottom row is the single node 20, and the subtree made of it alone is the answer.

Constraints
  • 1 ≤ number of nodes ≤ 500
  • 0 ≤ Node.val ≤ 500
  • All node values are distinct
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsTree Columns, Top Down MediumWhere the Deepest Leaves Meet MediumHops Between Two Keys MediumSpread Through the Tree MediumReplace With Cousin Sums Medium
loading Python…
Input
root=tree_node([7, 2, 9, 4, 6, None, 1, None, None, 3, 8])
Expected
[6, 3, 8]

Run checks the first 3 tests in your browser. Submit checks all 114 tests on the server, hidden ones included.