From ae73632585c7fec9a08a14e04c248168e58747ee Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=9C=D0=B8=D1=85=D0=B0=D0=B8=D0=BB=20=D0=92=D0=B0=D1=81?= =?UTF-8?q?=D0=B8=D0=BB=D1=8C=D0=B5=D0=B2?= Date: Sat, 28 Feb 2026 11:03:18 +0300 Subject: [PATCH] feat: 1448. Count Good Nodes in Binary Tree --- .../__init__.py | 0 .../solution.py | 23 +++++++++++++++++++ tests/test_count-good-nodes-in-binary-tree.py | 13 +++++++++++ 3 files changed, 36 insertions(+) create mode 100644 src/binary_tree/dfs/count_good_nodes_in_binary_tree/__init__.py create mode 100644 src/binary_tree/dfs/count_good_nodes_in_binary_tree/solution.py create mode 100644 tests/test_count-good-nodes-in-binary-tree.py diff --git a/src/binary_tree/dfs/count_good_nodes_in_binary_tree/__init__.py b/src/binary_tree/dfs/count_good_nodes_in_binary_tree/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/binary_tree/dfs/count_good_nodes_in_binary_tree/solution.py b/src/binary_tree/dfs/count_good_nodes_in_binary_tree/solution.py new file mode 100644 index 0000000..e47dc37 --- /dev/null +++ b/src/binary_tree/dfs/count_good_nodes_in_binary_tree/solution.py @@ -0,0 +1,23 @@ +from structures import TreeNode + + +class Solution: + def good_w_max(self, cur_max, root: TreeNode) -> int: + if root: + counter = 0 + if root.val >= cur_max: + counter += 1 + cur_max = max(cur_max, root.val) + return ( + counter + + self.good_w_max(cur_max, root.left) + + self.good_w_max(cur_max, root.right) + ) + return 0 + + def goodNodes(self, root: TreeNode) -> int: + return ( + 1 + + self.good_w_max(root.val, root.left) + + self.good_w_max(root.val, root.right) + ) diff --git a/tests/test_count-good-nodes-in-binary-tree.py b/tests/test_count-good-nodes-in-binary-tree.py new file mode 100644 index 0000000..6495831 --- /dev/null +++ b/tests/test_count-good-nodes-in-binary-tree.py @@ -0,0 +1,13 @@ +import pytest +from src.binary_tree.dfs.count_good_nodes_in_binary_tree.solution import Solution +from test_utils import TreeBuilder + + +@pytest.mark.parametrize( + "root, expected", + [([3, 1, 4, 3, None, 1, 5], 4), ([3, 3, None, 4, 2], 3), ([1], 1)], +) +def test_max_depth(root, expected): + root = TreeBuilder.from_list(root) + solution = Solution() + assert solution.goodNodes(root) == expected