Skip to content

Fix BinarySearchTree.search comparing values by identity - #15817

Closed
JayPokale wants to merge 1 commit into
TheAlgorithms:masterfrom
JayPokale:fix-bst-search-identity-compare
Closed

JayPokale wants to merge 1 commit into
TheAlgorithms:masterfrom
JayPokale:fix-bst-search-identity-compare

Conversation

@JayPokale

Copy link
Copy Markdown

Describe your change

  • Fix a bug or typo in an existing algorithm?

BinarySearchTree.search walks the tree with node.value is not value, which compares object identity instead of equality. A value that is equal to a stored one but is a different object is never found. This happens for ints outside CPython's small-int cache (above 256) and for floats:

>>> t = BinarySearchTree().insert(int("1000"), int("2000"))
>>> t.search(int("2000"))
None          # before; Node(2000) after
>>> t.remove(int("2000"))
ValueError: Value 2000 not found   # before; removes the node after

remove goes through search, so it fails the same way. The existing doctests only passed because small literals such as 10 or 50 are cached and share identity.

The fix is node.value != value. I added doctests for a large int and a float. They fail on master and pass with this change.

Checked with pytest --doctest-modules data_structures/binary_tree/binary_search_tree.py, ruff check and ruff format --check (ruff 0.17.3).

Checklist

  • I have read CONTRIBUTING.md.
  • This pull request is all my own work -- I have not plagiarized.
  • I know that pull requests will not be merged if they fail the automated tests.
  • This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
  • All functions and variable names follow Python naming conventions.
  • All functions have doctests that pass the automated testing.

@algorithms-keeper algorithms-keeper Bot added the awaiting reviews This PR is ready to be reviewed label Nov 27, 2026
@algorithms-keeper

Copy link
Copy Markdown

Multiple Pull Request Detected

@JayPokale, we are extremely excited that you want to submit multiple algorithms in this repository but we have a limit on how many pull request a user can keep open at a time. This is to make sure all maintainers and users focus on a limited number of pull requests at a time to maintain the quality of the code.

This pull request is being closed as the user already has an open pull request. Please focus on your previous pull request before opening another one. Thank you for your cooperation.

User opened pull requests (including this one): #15817, #15796, #15795, #15794, #15793, #15792, #15787, #15785, #15784, #15783, #15782, #15779, #15778

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

awaiting reviews This PR is ready to be reviewed

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant