-
Notifications
You must be signed in to change notification settings - Fork 0
/
NumberOfGoodLeafNodesPairs.py
45 lines (32 loc) · 1.2 KB
/
NumberOfGoodLeafNodesPairs.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
# 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 countPairs(self, root: TreeNode, distance: int) -> int:
self.pairs = 0
self._dfs(root, distance)
return self.pairs
def _dfs(self, root: TreeNode, distance: int) -> dict:
if root is None:
return defaultdict(int)
if root.left is None and root.right is None:
count = defaultdict(int)
count[1] = 1
return count
left_dist = self._dfs(root.left, distance)
right_dist = self._dfs(root.right, distance)
for dl in left_dist:
for dr in right_dist:
if dl + dr <= distance:
self.pairs += left_dist[dl] * right_dist[dr]
all_dist = defaultdict(int)
for d in left_dist:
if d + 1 <= distance:
all_dist[d + 1] = left_dist[d]
for d in right_dist:
if d + 1 <= distance:
all_dist[d + 1] += right_dist[d]
return all_dist