diff --git a/src/binary_search_tree/__init__.py b/src/binary_search_tree/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/binary_search_tree/search_in_a_binary_search_tree/__init__.py b/src/binary_search_tree/search_in_a_binary_search_tree/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/binary_search_tree/search_in_a_binary_search_tree/solution.py b/src/binary_search_tree/search_in_a_binary_search_tree/solution.py new file mode 100644 index 0000000..7f6353d --- /dev/null +++ b/src/binary_search_tree/search_in_a_binary_search_tree/solution.py @@ -0,0 +1,15 @@ +from typing import Optional +from structures import TreeNode + + +class Solution: + def searchBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]: + if not root: + return None + + if root.val == val: + return root + elif root.val > val: + return self.searchBST(root.left, val) + else: + return self.searchBST(root.right, val) diff --git a/test_utils/tree_builder.py b/test_utils/tree_builder.py index 50c1ad9..308b4a0 100644 --- a/test_utils/tree_builder.py +++ b/test_utils/tree_builder.py @@ -27,3 +27,25 @@ def from_list(values: list[Optional[int]]) -> Optional[TreeNode]: i += 1 return root + + @staticmethod + def to_list(root: Optional[TreeNode]) -> list[Optional[int]]: + if not root: + return [] + + result = [] + queue = deque([root]) + + while queue: + node = queue.popleft() + if node: + result.append(node.val) + queue.append(node.left) + queue.append(node.right) + else: + result.append(None) + + while result and result[-1] is None: + result.pop() + + return result diff --git a/tests/test_search_in_a_binary_search_tree.py b/tests/test_search_in_a_binary_search_tree.py new file mode 100644 index 0000000..10e9634 --- /dev/null +++ b/tests/test_search_in_a_binary_search_tree.py @@ -0,0 +1,13 @@ +import pytest +from src.binary_search_tree.search_in_a_binary_search_tree.solution import Solution +from test_utils import TreeBuilder + + +@pytest.mark.parametrize( + "root, val, expected", + [([4, 2, 7, 1, 3], 2, [2, 1, 3]), ([4, 2, 7, 1, 3], 5, [])], +) +def test_search_bst(root, val, expected): + root = TreeBuilder.from_list(root) + solution = Solution() + assert TreeBuilder.to_list(solution.searchBST(root, val)) == expected