Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Empty file.
23 changes: 23 additions & 0 deletions src/binary_tree/dfs/count_good_nodes_in_binary_tree/solution.py
Original file line number Diff line number Diff line change
@@ -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)
)
13 changes: 13 additions & 0 deletions tests/test_count-good-nodes-in-binary-tree.py
Original file line number Diff line number Diff line change
@@ -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