Profile

Unblock all features

Sign in to track progress and visualise your code.

ntree.ai
Linked lists, trees and graphs

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.

4
2
1
3
6
5
1, 2, 3 are less than 4, and 5, 6 are greater

Time complexity

operationtime
search for a valueO(h)O(h)
insert a nodeO(h)O(h)
delete a nodeO(h)O(h)

hh 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.

search 3
4
2
1
3
6
5
node = 4, 3 < 4, go left
1 / 3

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.

insert 5
4
2
1
3
6
node = 4, 5 > 4, go right
1 / 3

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.
delete 4
4
2
1
3
6
5
node = 4, found 4, it has two children
1 / 5

Balanced trees

Searching in a binary search tree takes O(h)O(h) time, which is O(log⁡n)O(\log n) when the tree is balanced. If every node has only one child, the tree becomes a line and search takes O(n)O(n) time.

1
2
3
insert 1, 2, 3: height 3
2
1
3
balanced: height 2

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 O(log⁡n)O(\log n).

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.

Build a binary search tree
Python
# Definitions:
# class BinaryTreeNode:
# def __init__(self, val=0):
# self.val = val
# self.left = None
# self.right = None
class BinarySearchTree:
def __init__(self) -> None:
self.root = None
def insert(self, val: int) -> None:
# Insert val into the tree
pass
def contains(self, val: int) -> bool:
# Return True when val is in the tree
return False
def delete(self, val: int) -> None:
# Delete val from the tree
pass
tree = BinarySearchTree()
for val in [4, 2, 6, 1, 3]:
tree.insert(val)
print(tree.contains(3))
for val in [1, 6, 4]:
tree.delete(val)
print(tree.contains(1))
Was this lesson helpful?