-
-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy path0865-smallest-subtree-with-all-the-deepest-nodes.py
More file actions
45 lines (33 loc) · 1.16 KB
/
0865-smallest-subtree-with-all-the-deepest-nodes.py
File metadata and controls
45 lines (33 loc) · 1.16 KB
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
# time complexity: O(n)
# space complexity: O(n)
from typing import Optional
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def subtreeWithAllDeepest(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
def dfs(node, depth):
if not node:
return (None, depth)
leftLca, leftDepth = dfs(node.left, depth + 1)
rightLca, rightDepth = dfs(node.right, depth + 1)
if leftDepth > rightDepth:
return (leftLca, leftDepth)
elif rightDepth > leftDepth:
return (rightLca, rightDepth)
else:
return (node, leftDepth)
lcaNode, _ = dfs(root, 0)
return lcaNode
root = TreeNode(3)
root.left = TreeNode(5)
root.right = TreeNode(1)
root.left.left = TreeNode(6)
root.left.right = TreeNode(2)
root.right.left = TreeNode(0)
root.right.right = TreeNode(8)
root.left.right.left = TreeNode(7)
root.left.right.right = TreeNode(4)
print(Solution().subtreeWithAllDeepest(root))