Given a Binary Search Tree (BST) and a target value, your task is to determine whether this value exists in the BST. If it does, return the node that contains this value; otherwise, return null
or indicate that the value is not found.
Find a Value in a BST - Algorithm, Visualization, Examples
⬅ Previous TopicFind All Duplicate Subtrees in a Binary Tree
Next Topic ⮕Delete a Node in a Binary Search Tree
Next Topic ⮕Delete a Node in a Binary Search Tree
Visualization Player
Solution
Algorithm Steps
Code
Python
Java
JavaScript
C
C++
C#
Go
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")