-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1448.count-good-nodes-in-binary-tree.py
More file actions
56 lines (44 loc) · 1.62 KB
/
1448.count-good-nodes-in-binary-tree.py
File metadata and controls
56 lines (44 loc) · 1.62 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
46
47
48
49
50
51
52
53
54
55
56
# 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
# Recursive Solution - doesn't look elegant, the last one does!
class Solution_one:
def goodNodes(self, root: TreeNode) -> int:
def _goodNodes(node: TreeNode, max_value: int) -> int:
max_value = max(max_value, node.val)
left = _goodNodes(node.left, max_value) if node.left else 0
right = _goodNodes(node.right, max_value) if node.right else 0
return left + right + 1 if node.val >= max_value else left + right
return _goodNodes(root, root.val)
class Solution_two:
def goodNodes(self, root: TreeNode) -> int:
ans = 0
stack: list[tuple[TreeNode, int]] = [(root, root.val)]
while stack:
node, value = stack.pop()
value = max(value, node.val)
if node.right:
stack.append((node.right, value))
if node.left:
stack.append((node.left, value))
if node.val >= value:
ans += 1
return ans
# @leet start
class Solution:
def goodNodes(self, root: TreeNode) -> int:
def dfs(node: TreeNode, max_path) -> int:
ans = 0
if node.val >= max_path:
ans += 1
max_path = max(max_path, node.val)
if node.left:
ans += dfs(node.left, max_path)
if node.right:
ans += dfs(node.right, max_path)
return ans
return dfs(root, root.val)
# @leet end