-
Notifications
You must be signed in to change notification settings - Fork 0
/
8_UnivalCount.py
37 lines (28 loc) · 1.01 KB
/
8_UnivalCount.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
# Solution 1
def is_unival(root):
return unival_helper(root, root.value)
def unival_helper(root, value):
if root is None:
return True
if root.value == value:
return unival_helper(root.left, value) and unival_helper(root.right, value)
return False
def count_unival_subtrees(root):
# Solution 2
def count_unival_subtrees(root):
count, _ = helper(root)
return count
# Also returns number of unival subtrees, and whether it is itself a unival subtree.
def helper(root):
if root is None:
return 0, True
left_count, is_left_unival = helper(root.left)
right_count, is_right_unival = helper(root.right)
total_count = left_count + right_count
if is_left_unival and is_right_unival:
if root.left is not None and root.value != root.left.value:
return total_count, False
if root.right is not None and root.value != root.right.value:
return total_count, False
return total_count + 1, True
return total_count, False