Binary Search Tree
A BST guarantees the BST property: every node in the left subtree is smaller, every node in the right subtree is larger. This enables O(log n) search, insert, and delete on a balanced tree.
class BSTNode {
val: number;
left: BSTNode | null; // val < this.val
right: BSTNode | null; // val > this.val
}Insert
Search
Delete
Want to see how the recursive code works?
Copy this code and paste it in the Recursion Tracer to visualize the call stack step-by-step.
class BSTNode {
constructor(val) {
this.val = val;
this.left = null;
this.right = null;
}
}
function insert(root, val) {
if (!root) return new BSTNode(val);
if (val < root.val) root.left = insert(root.left, val);
else if (val > root.val) root.right = insert(root.right, val);
return root;
}
function buildBST(arr) {
let root = null;
for (const val of arr) root = insert(root, val);
return root;
}
function inorder(node) {
if (!node) return [];
return [...inorder(node.left), node.val, ...inorder(node.right)];
}
// Build and traverse
const input = [5, 3, 7, 1, 4, 6, 8];
const root = buildBST(input);
console.log("Inorder:", inorder(root));
// Inorder of a BST always gives sorted output!