class TreeNode {
val: number;
left: TreeNode | null;
right: TreeNode | null;
constructor(val: number) {
this.val = val;
this.left = null;
this.right = null;
}
}
function searchBST(root: TreeNode | null, val: number): TreeNode | null {
if (root === null) return null; // base case: empty tree or not found
if (root.val === val) return root; // found the value
if (val < root.val) {
return searchBST(root.left, val); // go left if val smaller
} else {
return searchBST(root.right, val); // go right if val bigger
}
}
// Build the example tree
const root = new TreeNode(10);
root.left = new TreeNode(5);
root.right = new TreeNode(15);
root.left.left = new TreeNode(3);
root.left.right = new TreeNode(7);
root.right.right = new TreeNode(20);
const result = searchBST(root, 7);
if (result) {
console.log(`Found ${result.val}`);
} else {
console.log("Value not found");
}if (root === null) return null; // base case: empty tree or not found
stop search if reached empty spot
if (root.val === val) return root; // found the value
check if current node has the value
if (val < root.val) {
return searchBST(root.left, val); // go left if val smaller
} else {
return searchBST(root.right, val); // go right if val bigger
}
decide direction based on BST property