forked from ngiengkianyew/daily-coding-problem
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproblem_196.py
More file actions
34 lines (24 loc) · 679 Bytes
/
problem_196.py
File metadata and controls
34 lines (24 loc) · 679 Bytes
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
class Node:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def get_freq_tree_sum(root, counts):
if not root:
return 0
tree_sum = root.val + \
get_freq_tree_sum(root.left, counts) + \
get_freq_tree_sum(root.right, counts)
if not tree_sum in counts:
counts[tree_sum] = 0
counts[tree_sum] += 1
return tree_sum
def get_freq_tree_sum_helper(root):
counts = dict()
get_freq_tree_sum(root, counts)
return max(counts.items(), key=lambda x: x[1])[0]
# Tests
root = Node(5)
root.left = Node(2)
root.right = Node(-5)
assert get_freq_tree_sum_helper(root) == 2