Find a Value in a Binary Search Tree

Find a Value in a Binary Search Tree

Visualization

Algorithm Steps

  1. Given a Binary Search Tree (BST) and a target value.
  2. Start at the root node of the BST.
  3. If the current node is null, the target is not found; return null.
  4. If the current node's value equals the target, return the current node.
  5. If the target is less than the current node's value, recursively search the left subtree.
  6. If the target is greater than the current node's value, recursively search the right subtree.

Find a Value in a BST Program Code

Python
Java
JavaScript
C
C++
C#
Kotlin
Swift
Go
Php
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

def find_in_bst(root, target):
    if root is None:
        return None
    if root.val == target:
        return root
    elif target < root.val:
        return find_in_bst(root.left, target)
    else:
        return find_in_bst(root.right, target)

# Example usage:
if __name__ == '__main__':
    # Construct a simple BST
    root = TreeNode(10, TreeNode(5), TreeNode(15))
    target = 5
    result = find_in_bst(root, target)
    if result:
        print(f"Found node with value: {result.val}")
    else:
        print("Value not found")