- Home
- /
- Tutorials
- /
- DSA Tutorial
- /
- Binary Search Trees
Trees
Binary Search Trees
A binary search tree is a sorted array that is cheap to insert into. Its whole advantage disappears the moment it becomes unbalanced, which happens on the most ordinary input there is: sorted data.
The one rule
For every node: everything in the left subtree is smaller, everything in the right subtree is larger. Applied recursively, at every node - not just the immediate children.
Search and insert
javascript
function search(node, target) {
if (!node) return null
if (node.value === target) return node
// Half the tree is eliminated at every step.
return target < node.value
? search(node.left, target)
: search(node.right, target)
}
function insert(node, value) {
if (!node) return new TreeNode(value)
if (value < node.value) node.left = insert(node.left, value)
else if (value > node.value) node.right = insert(node.right, value)
return node // equal values ignored
}