-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path1448.py
114 lines (92 loc) · 3.07 KB
/
1448.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
# [ LeetCode ] 1448. Count Good Nodes in Binary Tree
def solution(root: "TreeNode") -> int:
def preorder_traversal(maximum_number: int, node: "TreeNode") -> None:
nonlocal answer
if node:
if node.val >= maximum_number:
answer += 1
maximum_number = node.val
preorder_traversal(
maximum_number=maximum_number,
node=node.left
)
preorder_traversal(
maximum_number=maximum_number,
node=node.right
)
answer: int = 0
maximum_number: int = (-10 ** 4 - 1)
preorder_traversal(maximum_number=maximum_number, node=root)
return answer
def another_solution(root: "TreeNode") -> int:
from collections import deque
answer: int = 0
queue: deque = deque()
queue.append((root, root.val))
while queue:
node, maximum_number = queue.popleft()
if node.val >= maximum_number:
answer += 1
maximum_number = node.val
if node.left:
queue.append((node.left, maximum_number))
if node.right:
queue.append((node.right, maximum_number))
return answer
if __name__ == "__main__":
class TreeNode:
def __init__(self, val, left= None, right= None) -> None:
self.val = val
self.left = left
self.right = right
def create_binary_tree(index: int, items: list[int]) -> TreeNode:
N: int = len(items)
if items[index]:
root: TreeNode = TreeNode(val=items[index])
if index * 2 + 1 < N:
root.left = create_binary_tree(
index=index * 2 + 1, items=items
)
if index * 2 + 2 < N:
root.right = create_binary_tree(
index=index * 2 + 2, items=items
)
return root
else:
return None
cases: list[dict[str, dict[str, list[int]] | int]] = [
{
"input": {
"TreeNode": [3, 1, 4, 3, None, 1, 5]
},
"output": 4
},
{
"input": {
"TreeNode": [3, 3, None, 4, 2]
},
"output": 3
},
{
"input": {
"TreeNode": [1]
},
"output": 1
},
{
"input": {
"TreeNode": [
-1, 5, -2, 4, 4, 2, -2, None, None, -4, None, -2, 3,
None, -2, 0, None, -1, None, -3, None, -4, -3, 3, None,
None, None, None, None, None, None, 3, -3
]
},
"output": 5
}
]
for case in cases:
root: TreeNode = create_binary_tree(
index=0, items=case["input"]["TreeNode"]
)
assert case["output"] == solution(root=root)
assert case["output"] == another_solution(root=root)