Skip to content

Conversation

@BrianLusina
Copy link
Owner

@BrianLusina BrianLusina commented Oct 28, 2025

Describe your change:

An algorithm to find the closest value in a binary search tree using breadth first search approach iteratively using a first in first out queue to find the closest value to the provided target value.

  • Add an algorithm?
  • Fix a bug or typo in an existing algorithm?
  • Documentation change?

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 new Python files are placed inside an existing directory.
  • All filenames are in all lowercase characters with no spaces or dashes.
  • All functions and variable names follow Python naming conventions.
  • All function parameters and return values are annotated with Python type hints.
  • All functions have doctests that pass the automated testing.
  • All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
  • If this pull request resolves one or more open issues then the commit message contains Fixes: #{$ISSUE_NO}.

Summary by CodeRabbit

  • New Features

    • Added "Find Closest Value in BST" problem to the binary search collection
    • Added functionality to locate the closest value in a BST
  • Documentation

    • Added full problem guide with examples, hints, and complexity notes
    • Minor formatting tweaks to an existing README
  • Tests

    • Added unit tests validating the new closest-value behavior

@BrianLusina BrianLusina self-assigned this Oct 28, 2025
@BrianLusina BrianLusina added hacktoberfest-accepted Hacktoberfest Algorithm Algorithm Problem Datastructures Datastructures Binary Search Binary Search Algorithm labels Oct 28, 2025
@coderabbitai
Copy link

coderabbitai bot commented Oct 28, 2025

Note

Currently processing new changes in this PR. This may take a few minutes, please wait...

📥 Commits

Reviewing files that changed from the base of the PR and between 1d8d377 and fb749bd.

📒 Files selected for processing (2)
  • datastructures/trees/binary/search_tree/__init__.py (1 hunks)
  • puzzles/search/binary_search/find_closest_value/__init__.py (1 hunks)
 _______________________________________________________________________________________________
< bm = Δc/Δt: Bug momentum equals change in code over change in time. Can't argue with physics. >
 -----------------------------------------------------------------------------------------------
  \
   \   \
        \ /\
        ( )
      .( o ).

Tip

You can disable sequence diagrams in the walkthrough.

Disable the reviews.sequence_diagrams setting in your project's settings in CodeRabbit to disable sequence diagrams in the walkthrough.

Walkthrough

A new "Find Closest Value in BST" puzzle is introduced with a function implementation using breadth-first search traversal to locate the node with the smallest absolute difference to a target value. Corresponding documentation, tests, a BST class method, and directory listing updates are included.

Changes

Cohort / File(s) Summary
Directory and documentation
DIRECTORY.md, puzzles/search/binary_search/find_closest_number/README.md, puzzles/search/binary_search/find_closest_value/README.md
Added directory entry for new puzzle; minor README formatting fix; new README documenting the Find Closest Value in BST problem with statement, examples, hints, and complexity notes.
Core puzzle implementation
puzzles/search/binary_search/find_closest_value/__init__.py
New function find_closest_value_in_bst(node, target) that performs BFS traversal to find the node with absolute value closest to target, returning the closest value or None for empty input.
Data structure method
datastructures/trees/binary/search_tree/__init__.py
Added method find_closest_value_in_bst(target) to BinarySearchTree class, implementing equivalent BFS logic to find the closest-valued node.
Test coverage
puzzles/search/binary_search/find_closest_value/test_find_closest_value.py
New unit test module verifying find_closest_value_in_bst with a constructed BST, targeting value 12 and asserting result equals 13.

Sequence Diagram(s)

sequenceDiagram
    participant Caller
    participant Function as find_closest_value_in_bst
    participant Queue
    participant Node as BinaryTreeNode

    Caller->>Function: call with target value
    alt Empty tree
        Function-->>Caller: return None
    else Root matches target
        Function-->>Caller: return root.data
    else Traverse tree
        Function->>Queue: initialize with root
        loop Process nodes
            Function->>Queue: dequeue node
            Function->>Node: get node.data
            Function->>Function: calculate diff = abs(target - node.data)
            alt diff < current min
                Function->>Function: update closest_value
            end
            alt left child exists
                Function->>Queue: enqueue left
            end
            alt right child exists
                Function->>Queue: enqueue right
            end
        end
        Function-->>Caller: return closest_value
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

  • Duplication concern: The same BFS logic for finding closest value appears in two separate locations (puzzles/__init__.py and datastructures/__init__.py). Verify consistency between both implementations and confirm whether the duplication is intentional or if refactoring to a shared utility is needed.
  • Logic validation: Confirm the BFS traversal correctly tracks and updates the closest value across all nodes and handles edge cases (empty tree, single node, target equals a node value).
  • Test coverage: The test file contains only one assertion; verify whether additional test cases covering edge cases (empty tree, negative values, target at boundaries) are needed.

Poem

🐰 A closest value quest through trees we seek,
With queues and nodes, a path not bleak,
BFS hops through branches wide,
To find the value drawing nigh—
New puzzles bloom in search's light! 🌳

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 60.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Title Check ✅ Passed The pull request title "feat(datastructures, puzzles): find the closest value in a binary search tree" clearly and concisely describes the primary change across the changeset. It accurately reflects the addition of a new algorithm to find the closest value in a binary search tree, which is evidenced by the changes to multiple supporting files including the new implementation in puzzles/search/binary_search/find_closest_value/init.py, documentation in README.md, and test coverage. The title uses a conventional commit format with appropriate scope indicators and is specific enough to convey the main purpose of the PR without being overly verbose or misleading.
Description Check ✅ Passed The pull request description follows the required template structure and is substantially complete. It includes a filled "Describe your change" section that describes the algorithm and its approach, appropriately marks the change as adding an algorithm and making documentation changes, and provides a comprehensive checklist with all required items checked off by the contributor. The description demonstrates that the contributor has reviewed the CONTRIBUTING guidelines, included type hints, added doctests, created appropriate documentation with URLs, and followed naming conventions. The provided details align with the actual file changes shown in the raw_summary.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

🧹 Nitpick comments (3)
puzzles/search/binary_search/find_closest_value/test_find_closest_value.py (1)

7-7: Rename test method to be descriptive.

The test method name test_something is too generic and doesn't convey what is being tested.

Apply this diff to improve test clarity:

-    def test_something(self):
+    def test_find_closest_value_in_bst_returns_closest_value(self):
DIRECTORY.md (1)

548-549: Fix list indentation to match project style.

The indentation for these list items is inconsistent with the expected formatting.

Apply this diff to fix the indentation:

-      * Find Closest Value
-        * [Test Find Closest Value](https://github.com/BrianLusina/PythonSnips/blob/master/puzzles/search/binary_search/find_closest_value/test_find_closest_value.py)
+    * Find Closest Value
+      * [Test Find Closest Value](https://github.com/BrianLusina/PythonSnips/blob/master/puzzles/search/binary_search/find_closest_value/test_find_closest_value.py)
puzzles/search/binary_search/find_closest_value/__init__.py (1)

6-42: Consider refactoring to reduce code duplication.

This function has very similar logic to the find_closest_value_in_bst method in datastructures/trees/binary/search_tree/__init__.py (lines 222-266). The main difference is that this returns an integer value while the BST method returns a node. Consider whether one implementation could call the other to reduce duplication.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 3c5ac87 and 1d8d377.

📒 Files selected for processing (6)
  • DIRECTORY.md (1 hunks)
  • datastructures/trees/binary/search_tree/__init__.py (1 hunks)
  • puzzles/search/binary_search/find_closest_number/README.md (1 hunks)
  • puzzles/search/binary_search/find_closest_value/README.md (1 hunks)
  • puzzles/search/binary_search/find_closest_value/__init__.py (1 hunks)
  • puzzles/search/binary_search/find_closest_value/test_find_closest_value.py (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (3)
puzzles/search/binary_search/find_closest_value/__init__.py (2)
datastructures/queues/__init__.py (1)
  • Queue (7-66)
datastructures/trees/binary/search_tree/__init__.py (1)
  • find_closest_value_in_bst (222-266)
datastructures/trees/binary/search_tree/__init__.py (3)
puzzles/search/binary_search/find_closest_value/__init__.py (1)
  • find_closest_value_in_bst (6-42)
datastructures/trees/binary/node.py (1)
  • BinaryTreeNode (6-184)
datastructures/queues/fifo/__init__.py (1)
  • FifoQueue (6-62)
puzzles/search/binary_search/find_closest_value/test_find_closest_value.py (2)
datastructures/trees/binary/search_tree/__init__.py (1)
  • find_closest_value_in_bst (222-266)
puzzles/search/binary_search/find_closest_value/__init__.py (1)
  • find_closest_value_in_bst (6-42)
🪛 markdownlint-cli2 (0.18.1)
DIRECTORY.md

548-548: Unordered list indentation
Expected: 4; Actual: 6

(MD007, ul-indent)


549-549: Unordered list indentation
Expected: 6; Actual: 8

(MD007, ul-indent)

🔇 Additional comments (1)
puzzles/search/binary_search/find_closest_value/README.md (1)

1-43: LGTM!

The documentation is well-structured and provides clear guidance on the problem, including helpful hints and complexity analysis.

@BrianLusina BrianLusina merged commit 1aff4bb into main Oct 29, 2025
5 of 8 checks passed
@BrianLusina BrianLusina deleted the feat/find-closest-value-bst branch October 29, 2025 09:34
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Algorithm Algorithm Problem Binary Search Binary Search Algorithm Datastructures Datastructures hacktoberfest-accepted Hacktoberfest

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants