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 findMin(root: TreeNode | null): number | null {
if (root === null) return null;
let curr = root;
while (curr.left !== null) {
curr = curr.left; // advance curr to left child to find smaller value
}
return curr.val; // curr is now the smallest element
}
// Driver code to build the BST and find minimum
const root = new TreeNode(10,
new TreeNode(5,
new TreeNode(2,
new TreeNode(1),
null
),
null
),
new TreeNode(15)
);
const minVal = findMin(root);
console.log(minVal !== null ? `${minVal} -> null` : "Tree is empty");while (curr.left !== null) {
keep moving left to find smaller values
curr = curr.left; // advance curr to left child to find smaller value
advance curr pointer to left child
return curr.val; // curr is now the smallest element
return the value of the leftmost node