Algorithm Steps
- Given a Binary Search Tree (BST) and a target value.
- Start at the
root
node of the BST. - If the current node is
null
, the target is not found; returnnull
. - If the current node's value equals the target, return the current node.
- If the target is less than the current node's value, recursively search the left subtree.
- 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")