Binary Search Tree
A binary search tree is a tree where each node has at most 2 children, and for each node all the nodes in its left subtree have smaller values and all the nodes in its right subtree have bigger values.
These rules enable more efficient search but introduce additional logic on every insert and delete.
Time complexity
| operation | time |
|---|---|
| search for a value | |
| insert a node | |
| delete a node |
is the height of the tree.
Implementation
Search for a value
Given a binary search tree and a target, check if the target is in the tree.
At each node the value says which subtree can hold the target, so the other subtree is skipped.
Insert a node
Given a binary search tree and a value, insert the value into the tree.
Insert follows the same path as search. We follow the subtree that can hold the new value and once we reach an empty pointer, the new node should be added there.
Delete a node
Given a binary search tree and a value, delete the value from the tree.
We need to find the node with this value and remove it. Depending on how many children the node has:
- A node without children should be simply removed.
- A node with one child should be replaced by that child.
- A node with two children should be replaced by the smallest value in its right subtree.
Balanced trees
Searching in a binary search tree takes time, which is when the tree is balanced. If every node has only one child, the tree becomes a line and search takes time.
That is why self-balancing binary search trees exist, like an AVL tree or a red-black tree. These trees rearrange nodes after every insert and delete to keep their height as .
Interviews rarely ask you to implement those types of trees, but you should know why the balance matters.
Build it
Implement insert, search and delete in the class below.