Binary Search Tree (BST) explained: BST property, search, insertion, deletion operations, traversals, and code examples.
A Binary Search Tree (BST) is a hierarchical node-based data structure where each node contains a key. The key in any node is greater than all keys in its left subtree and smaller than all keys in its right subtree.
This property makes searching, insertion, and deletion performable in O(log n) time on balanced trees. An in-order traversal of a BST visits the keys in perfectly sorted ascending order.
Start at the root node and compare the target value with the current node key.
If target < currentNode.val, move to the left child. If target > currentNode.val, move to the right child.
If target === currentNode.val, the search succeeds. If a null pointer is encountered, the key does not exist in the BST.
To insert a new value, traverse down to the appropriate null position and attach the new node as a leaf.
1class TreeNode {2 constructor(val) {3 this.val = val;4 this.left = null;5 this.right = null;6 }7}8 9class BinarySearchTree {10 constructor() {11 this.root = null;12 }13 14 insert(val) {15 const newNode = new TreeNode(val);16 if (!this.root) {17 this.root = newNode;18 return this;19 }20 let current = this.root;21 while (true) {22 if (val === current.val) return undefined;23 if (val < current.val) {24 if (!current.left) {25 current.left = newNode;26 return this;27 }28 current = current.left;29 } else {30 if (!current.right) {31 current.right = newNode;32 return this;33 }34 current = current.right;35 }36 }37 }38 39 search(val) {40 let current = this.root;41 while (current) {42 if (val === current.val) return true;43 current = val < current.val ? current.left : current.right;44 }45 return false;46 }47 48 inOrderTraversal(node = this.root, result = []) {49 if (node) {50 this.inOrderTraversal(node.left, result);51 result.push(node.val);52 this.inOrderTraversal(node.right, result);53 }54 return result;55 }56}Play through every comparison, swap, and state change, adjust the speed, or enter custom inputs to test edge cases.
The full interactive roadmap is unlocking — these specialized modules land in upcoming releases.
This feature will be implemented in the next update.
This feature will be implemented in the next update.
This feature will be implemented in the next update.
Explore the full catalog — 30+ algorithms with more unlocking every release.
Step-by-step tree structure & key lookup path inspector
Test your understanding of Binary Search Tree (BST) complexity and step mechanics.
Q1.Which traversal on a Binary Search Tree produces values in strictly sorted ascending order?
Q2.What is the worst-case search time complexity of an unbalanced BST with n elements?
Apply Binary Search Tree (BST) to real coding interview questions.
Determine if a given binary tree is a valid Binary Search Tree.
Find the lowest common ancestor (LCA) node of two given nodes in a BST.