Smallest Subtree with all the Deepest Nodes

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.

30:00

Smallest Subtree with all the Deepest Nodes
medium
Free written solution
Topics
Companies

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.

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 will be in the range [1,500][1, 500].

  • 0≤0 \le Node.val ≤500\le 500

  • 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]}

Each call returns two things: the height of its subtree and the smallest node covering all of that subtree's deepest nodes. Heights decide which side the deepest nodes live on.

stack: (empty)
d1d2d3d4351620874
recursion stack
returned (h = height)
candidate passed up
deepest nodes
answer subtree
Variables
VariableValue
nodes9
DepthFunction Call
Stack empty
0/19