From ac2fd5ba92ba93fbbec17de126509d1d0c82153c Mon Sep 17 00:00:00 2001 From: Jay Pokale Date: Fri, 27 Nov 2026 15:11:30 +0530 Subject: [PATCH] Fix BinarySearchTree.search comparing values by identity --- data_structures/binary_tree/binary_search_tree.py | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/data_structures/binary_tree/binary_search_tree.py b/data_structures/binary_tree/binary_search_tree.py index 16b7b6b1ede2..df95854a5eeb 100644 --- a/data_structures/binary_tree/binary_search_tree.py +++ b/data_structures/binary_tree/binary_search_tree.py @@ -219,13 +219,22 @@ def search(self, value) -> Node | None: Traceback (most recent call last): ... IndexError: Warning: Tree is empty! please use another. + + Values are compared by equality, not identity, so equal ints that are + different objects (and equal floats) are found: + + >>> tree = BinarySearchTree().insert(int("1000"), int("2000")) + >>> tree.search(int("2000")).value + 2000 + >>> BinarySearchTree().insert(1.5, 2.5).search(float("2.5")).value + 2.5 """ if self.empty(): raise IndexError("Warning: Tree is empty! please use another.") node = self.root # use lazy evaluation here to avoid NoneType Attribute error - while node is not None and node.value is not value: + while node is not None and node.value != value: node = node.left if value < node.value else node.right return node