Assumption: The data stored in the tree (the keys) can be ordered and there are no duplicates (i.e., a total order).
Definition: A binary search tree is a binary tree where the key for each node is greater than the keys of all the nodes in its left subtree and less than all the keys in the nodes in its right subtree. This order property can be written as
Binary search trees are one of the most important tree structures used to find elements quickly.
-
Insertion: Descend the tree (smaller keys go to the left and larger keys go to the right) till a new leaf can be created.
-
Find
$x$ : Follow the tree down (maybe using recursion).- Return failure if the current node does not exist (we followed a
nullptr
). - Return node if the current node
$c == x$ . - if
$x < c$ go to left child, otherwise go right child. Go back to 1st step.
- Return failure if the current node does not exist (we followed a
-
Deletion:
- Find the node to delete using binary search.
- Cases:
- A. No children: Just remove the node.
- B. One child case: replace the node with the only child.
- C. Two children case: replace element with the smallest element in the right subtree.
- Insert the following numbers into a binary search tree: 12, 90, 3, 5, 18, 9, 99, 91
- Delete the following nodes from the tree: 3, 90
- Read the values in the tree using inorder traversal (LNR).
Since keys are stored in sorted order, a simple inorder traversal (LNR) results in sorted output.
If a balanced tree is used (see Balance Problem below), then inserting
See BinarySearchTree.h for code.
A depth
The exact depth of a complete tree (every level, except possibly the deepest, is entirely filled) with
Examples:
- A complete tree with 2,000,000 elements has
$d = log_2(2,000,000 + 1) - 1 \approx 20$ levels. - A complete tree with 2,000,000,000 elements has
$d = log_2(2,000,000,000 + 1) - 1 \approx 30$ levels.
Since
- Worst case insertion order is to insert sorted values which leads to a single branch of depth
$d = N - 1$ and therefore$O(N)$ time complexity. - Deletions for Case C replace a node with a node for the right subtree, resulting in an unbalanced tree that will become increasingly left heavy!
We need to add functionality to keep the tree balanced so we can achieve