From f40bc968a1621e8741e064f5b3374ade50ade1ac Mon Sep 17 00:00:00 2001 From: ivan Date: Sun, 5 Jan 2025 04:36:48 -0600 Subject: [PATCH] adding count complete nodes --- .../count_complete_nodes.py | 16 ++++++++++++++++ .../test_count_complete_nodes_round_12.py | 18 ++++++++++++++++++ 2 files changed, 34 insertions(+) create mode 100644 src/my_project/interviews/top_150_questions_round_12/count_complete_nodes.py create mode 100644 tests/test_150_questions_round_12/test_count_complete_nodes_round_12.py diff --git a/src/my_project/interviews/top_150_questions_round_12/count_complete_nodes.py b/src/my_project/interviews/top_150_questions_round_12/count_complete_nodes.py new file mode 100644 index 00000000..073d6638 --- /dev/null +++ b/src/my_project/interviews/top_150_questions_round_12/count_complete_nodes.py @@ -0,0 +1,16 @@ +from typing import List, Union, Collection, Mapping, Optional +from abc import ABC, abstractmethod + +class TreeNode: + def __init__(self, val=0, left=None, right=None): + self.val = val + self.left = left + self.right = right + +class Solution: + def countNodes(self, root: Optional[TreeNode]) -> int: + + if not root: + return 0 + else: + return self.countNodes(root.left) + self.countNodes(root.right) + 1 \ No newline at end of file diff --git a/tests/test_150_questions_round_12/test_count_complete_nodes_round_12.py b/tests/test_150_questions_round_12/test_count_complete_nodes_round_12.py new file mode 100644 index 00000000..35b91c00 --- /dev/null +++ b/tests/test_150_questions_round_12/test_count_complete_nodes_round_12.py @@ -0,0 +1,18 @@ +import unittest +from src.my_project.interviews.top_150_questions_round_12\ +.count_complete_nodes import TreeNode, Solution + +class CountNodesTestCase(unittest.TestCase): + + def test_count_none(self): + solution = Solution() + tree = None + output = solution.countNodes(root=tree) + self.assertEqual(0, output) + + + def test_count_non_empty_tree(self): + solution = Solution() + tree = TreeNode(1, TreeNode(2), TreeNode(3)) + output = solution.countNodes(root=tree) + self.assertEqual(3, output) \ No newline at end of file