⬅ Previous Topic
Find All Duplicate Subtrees in a Binary TreeNext Topic ⮕
Delete a Node in a Binary Search Tree⬅ Previous Topic
Find All Duplicate Subtrees in a Binary TreeNext Topic ⮕
Delete a Node in a Binary Search TreeTopic Contents
root
node of the BST.null
, the target is not found; return null
.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")
⬅ Previous Topic
Find All Duplicate Subtrees in a Binary TreeNext Topic ⮕
Delete a Node in a Binary Search TreeYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.