Leetcode 896 Solution
This article provides solution to leetcode question 896 (smallest-subtree-with-all-the-deepest-nodes)
Access this page by simply typing in "lcs 896" in your browser address bar if you have bunnylol configured.
Leetcode Question Link
https://leetcode.com/problems/smallest-subtree-with-all-the-deepest-nodes
Solution
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def subtreeWithAllDeepest(self, root: TreeNode) -> TreeNode:
self.ans = None
self.depth = -1
def dfs(node, depth):
if node is None:
return depth
left_depth = dfs(node.left, depth + 1)
right_depth = dfs(node.right, depth + 1)
if left_depth == right_depth and self.depth <= left_depth:
self.depth = left_depth
self.ans = node
return max(left_depth, right_depth)
dfs(root, 0)
return self.ans