Leetcode 1218 Solution

This article provides solution to leetcode question 1218 (lowest-common-ancestor-of-deepest-leaves)

https://leetcode.com/problems/lowest-common-ancestor-of-deepest-leaves

Solution

# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def lcaDeepestLeaves(self, root: Optional[TreeNode]) -> Optional[TreeNode]: max_depth = 0 max_depth_nodes = set()
def dfs(node, depth=0): nonlocal max_depth nonlocal max_depth_nodes
if not node: return
if depth > max_depth: max_depth = depth max_depth_nodes = {node} elif depth == max_depth: max_depth_nodes.add(node)
dfs(node.left, depth + 1) dfs(node.right, depth + 1)
dfs(root)
ans = None def find(node): nonlocal max_depth_nodes nonlocal ans
if not node: return 0
left_cnt = find(node.left) right_cnt = find(node.right)
if left_cnt > 0 and right_cnt > 0 and left_cnt + right_cnt == len(max_depth_nodes): ans = node elif left_cnt == 0 and right_cnt == 0 and node in max_depth_nodes and len(max_depth_nodes) == 1: ans = node
return int(node in max_depth_nodes) + left_cnt + right_cnt
find(root)
return ans