Skip to content

Commit dab76cc

Browse files
authored
feat: 1448. Count Good Nodes in Binary Tree (#39)
1 parent c285621 commit dab76cc

3 files changed

Lines changed: 36 additions & 0 deletions

File tree

src/binary_tree/dfs/count_good_nodes_in_binary_tree/__init__.py

Whitespace-only changes.
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
from structures import TreeNode
2+
3+
4+
class Solution:
5+
def good_w_max(self, cur_max, root: TreeNode) -> int:
6+
if root:
7+
counter = 0
8+
if root.val >= cur_max:
9+
counter += 1
10+
cur_max = max(cur_max, root.val)
11+
return (
12+
counter
13+
+ self.good_w_max(cur_max, root.left)
14+
+ self.good_w_max(cur_max, root.right)
15+
)
16+
return 0
17+
18+
def goodNodes(self, root: TreeNode) -> int:
19+
return (
20+
1
21+
+ self.good_w_max(root.val, root.left)
22+
+ self.good_w_max(root.val, root.right)
23+
)
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
import pytest
2+
from src.binary_tree.dfs.count_good_nodes_in_binary_tree.solution import Solution
3+
from test_utils import TreeBuilder
4+
5+
6+
@pytest.mark.parametrize(
7+
"root, expected",
8+
[([3, 1, 4, 3, None, 1, 5], 4), ([3, 3, None, 4, 2], 3), ([1], 1)],
9+
)
10+
def test_max_depth(root, expected):
11+
root = TreeBuilder.from_list(root)
12+
solution = Solution()
13+
assert solution.goodNodes(root) == expected

0 commit comments

Comments
 (0)