-
Notifications
You must be signed in to change notification settings - Fork 17
/
lowest-common-ancestor-of-deepest-leaves.py
67 lines (44 loc) · 1.8 KB
/
lowest-common-ancestor-of-deepest-leaves.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
from typing import Optional, Set
# 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]:
def find_deepest_leaves(root: TreeNode) -> Set[int]:
def max_depth_dfs(node: TreeNode) -> int:
return max(
(max_depth_dfs(node.left) + 1 if node.left else 0),
(max_depth_dfs(node.right) + 1 if node.right else 0),
)
max_depth = max_depth_dfs(root)
deepest_leaves: Set[int] = set()
def deepest_leaves_dfs(node: TreeNode, depth: int) -> None:
if node.left:
deepest_leaves_dfs(node.left, depth + 1)
if node.right:
deepest_leaves_dfs(node.right, depth + 1)
if depth == max_depth:
deepest_leaves.add(node.val)
deepest_leaves_dfs(root, 0)
return deepest_leaves
if not root:
return None
deepest_leaves = find_deepest_leaves(root)
lowest_common_ancestor: Optional[TreeNode] = None
def dfs(node: TreeNode) -> bool:
nonlocal lowest_common_ancestor
left, right = False, False
if node.left:
left = dfs(node.left)
if node.right:
right = dfs(node.right)
if (left and right) or (node.val in deepest_leaves):
lowest_common_ancestor = node
if left or right or (node.val in deepest_leaves):
return True
return False
dfs(root)
return lowest_common_ancestor