July 6th 2023

Search in a Binary Search Tree — Typescript

Problem Description permalink

You are given the root of a binary search tree (BST) and an integer val.

Find the node in the BST that the node's value equals val and return the subtree rooted with that node. If such a node does not exist, return null.

Solution permalink

/**
* Definition for a binary tree node.
* class TreeNode {
* val: number
* left: TreeNode | null
* right: TreeNode | null
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
* }
*/


function searchBST(root: TreeNode | null, val: number): TreeNode | null {
if (root == null){
return null;
}

if (root.val == val){
return root;
}

const left = searchBST(root.left, val);
if (left !== null){
return left;
}

const right = searchBST(root.right, val);
if (right !== null){
return right;
}

return null;
};

Discussion permalink

This is a depth-first search that will always search all the way down the tree on the left side, then the right side.