7.4 Binary search tree¶
As Figure 7-16 shows, a binary search tree satisfies the following conditions.
- At the root, every value in the left subtree \(<\) the root value \(<\) every value in the right subtree.
- The left and right subtrees of every node are themselves binary search trees, so they too satisfy condition
1..
Figure 7-16 Binary search tree
Description of Figure 7-16: Binary search tree containing 1 through 15
At every node of a binary search tree, all values in the left subtree must be smaller than the node's value and all values in the right subtree must be larger.
This binary search tree has four levels and 15 nodes with values 1 through 15. All edge arrows point from parent to child. The root at the first level is 8, with left child 4 and right child 12.
On the second level, node 4 has left child 2 and right child 6, and 12 has left child 10 and right child 14. Nodes at the third level point to the eight leaves on the fourth. The left and right children of 2 are 1 and 3, those of 6 are 5 and 7, those of 10 are 9 and 11, and those of 14 are 13 and 15.
The ordering of the binary search tree recurs in each subtree. At root 8, the left subtree contains 1 through 7, all smaller than 8, and the right subtree contains 9 through 15, all larger than 8. The same rule applies farther down. For example, the left subtree of 4 contains 1 through 3, all smaller than 4. Its right subtree contains 5 through 7, all larger than 4 and smaller than root 8.
7.4.1 Binary search tree operations¶
We implement the tree as a BinarySearchTree class with a member variable root that points to the root.
1. Search for a node¶
Given a target value num, we can use the search tree property to find it. As shown below, start a node reference cur at the root root and repeatedly compare the current value cur.val with num.
- If
cur.val < num, the target belongs in the right subtree ofcur, so setcur = cur.right. - If
cur.val > num, the target belongs in the left subtree ofcur, so setcur = cur.left. - If
cur.val = num, we have found the target. Exit the loop and return the node.
Figure 7-17 Searching for a node in a binary search tree
Description of Figure 7-17: Searching for node 7 in a binary search tree
Search for 7 in a binary search tree containing values 1 through 15. At each step, compare values and choose the left or right branch.
At every node of a binary search tree, all values in its left subtree are smaller than its own and all values in its right subtree are larger. Edge arrows point from parent to child.
The four-level perfect binary search tree contains nodes 1 through 15. Root 8 has left child 4 and right child 12. The left and right children of 4 are 2 and 6, and those of 12 are 10 and 14. The children of 2 are 1 and 3, those of 6 are 5 and 7, those of 10 are 9 and 11, and those of 14 are 13 and 15, in left-to-right order.
The pointer cur points to the node currently being checked, highlighted in solid blue. Blue arrows and blue rings around nodes mark the search path taken so far.
Start at root 8
Initialize cur to root 8, highlighted in solid blue. Compare target 7 with the current value 8. Since 7 < 8, the target must be in the left subtree, so the next move is down and left to child 4. The path so far is 8.
Go left to node 4
Since 7 < 8, set cur = cur.left to follow the blue arrow from 8 to left child 4. Compare target 7 with the current value 4. Since 7 > 4, turn next to the right subtree of 4. The path so far is 8→4.
Go right to node 6
Since 7 > 4, set cur = cur.right to follow the blue arrow from 4 to right child 6. Compare target 7 with the current value 6. Since 7 > 6, continue to the right child of 6. The path so far is 8→4→6.
Find node 7
Since 7 > 6, set cur = cur.right to follow the blue arrow from 6 to right child 7. The value at cur now equals the target 7. Exit the loop and return node 7. The path taken is 8→4→6→7.
The pointer cur compares four nodes along 8 → 4 → 6 → 7. At the fourth step it finds the target value 7 and returns that node. The search leaves all tree connections intact.
Searching a binary search tree uses the same principle as binary search: each round eliminates half the possibilities. The tree height bounds the number of iterations, and a balanced tree takes \(O(\log n)\) time. Here is an implementation:
def search(self, num: int) -> TreeNode | None:
"""Search for a node"""
cur = self._root
# Stop the search after passing a leaf
while cur is not None:
# The target is in the right subtree of cur
if cur.val < num:
cur = cur.right
# The target is in the left subtree of cur
elif cur.val > num:
cur = cur.left
# The target was found, so exit the loop
else:
break
return cur
/* Search for a node */
TreeNode *search(int num) {
TreeNode *cur = root;
// Stop the search after passing a leaf
while (cur != nullptr) {
// The target is in the right subtree of cur
if (cur->val < num)
cur = cur->right;
// The target is in the left subtree of cur
else if (cur->val > num)
cur = cur->left;
// The target was found, so exit the loop
else
break;
}
// Return the target node
return cur;
}
/* Search for a node */
TreeNode search(int num) {
TreeNode cur = root;
// Stop the search after passing a leaf
while (cur != null) {
// The target is in the right subtree of cur
if (cur.val < num)
cur = cur.right;
// The target is in the left subtree of cur
else if (cur.val > num)
cur = cur.left;
// The target was found, so exit the loop
else
break;
}
// Return the target node
return cur;
}
/* Search for a node */
TreeNode? Search(int num) {
TreeNode? cur = root;
// Stop the search after passing a leaf
while (cur != null) {
// The target is in the right subtree of cur
if (cur.val < num) cur =
cur.right;
// The target is in the left subtree of cur
else if (cur.val > num)
cur = cur.left;
// The target was found, so exit the loop
else
break;
}
// Return the target node
return cur;
}
/* Search for a node */
func (bst *binarySearchTree) search(num int) *TreeNode {
node := bst.root
// Stop the search after passing a leaf
for node != nil {
if node.Val.(int) < num {
// The target is in the right subtree of cur
node = node.Right
} else if node.Val.(int) > num {
// The target is in the left subtree of cur
node = node.Left
} else {
// The target was found, so exit the loop
break
}
}
// Return the target node
return node
}
/* Search for a node */
func search(num: Int) -> TreeNode? {
var cur = root
// Stop the search after passing a leaf
while cur != nil {
// The target is in the right subtree of cur
if cur!.val < num {
cur = cur?.right
}
// The target is in the left subtree of cur
else if cur!.val > num {
cur = cur?.left
}
// The target was found, so exit the loop
else {
break
}
}
// Return the target node
return cur
}
/* Search for a node */
search(num) {
let cur = this.root;
// Stop the search after passing a leaf
while (cur !== null) {
// The target is in the right subtree of cur
if (cur.val < num) cur = cur.right;
// The target is in the left subtree of cur
else if (cur.val > num) cur = cur.left;
// The target was found, so exit the loop
else break;
}
// Return the target node
return cur;
}
/* Search for a node */
search(num: number): TreeNode | null {
let cur = this.root;
// Stop the search after passing a leaf
while (cur !== null) {
// The target is in the right subtree of cur
if (cur.val < num) cur = cur.right;
// The target is in the left subtree of cur
else if (cur.val > num) cur = cur.left;
// The target was found, so exit the loop
else break;
}
// Return the target node
return cur;
}
/* Search for a node */
TreeNode? search(int _num) {
TreeNode? cur = _root;
// Stop the search after passing a leaf
while (cur != null) {
// The target is in the right subtree of cur
if (cur.val < _num)
cur = cur.right;
// The target is in the left subtree of cur
else if (cur.val > _num)
cur = cur.left;
// The target was found, so exit the loop
else
break;
}
// Return the target node
return cur;
}
/* Search for a node */
pub fn search(&self, num: i32) -> OptionTreeNodeRc {
let mut cur = self.root.clone();
// Stop the search after passing a leaf
while let Some(node) = cur.clone() {
match num.cmp(&node.borrow().val) {
// The target is in the right subtree of cur
Ordering::Greater => cur = node.borrow().right.clone(),
// The target is in the left subtree of cur
Ordering::Less => cur = node.borrow().left.clone(),
// The target was found, so exit the loop
Ordering::Equal => break,
}
}
// Return the target node
cur
}
/* Search for a node */
TreeNode *search(BinarySearchTree *bst, int num) {
TreeNode *cur = bst->root;
// Stop the search after passing a leaf
while (cur != NULL) {
if (cur->val < num) {
// The target is in the right subtree of cur
cur = cur->right;
} else if (cur->val > num) {
// The target is in the left subtree of cur
cur = cur->left;
} else {
// The target was found, so exit the loop
break;
}
}
// Return the target node
return cur;
}
/* Search for a node */
fun search(num: Int): TreeNode? {
var cur = root
// Stop the search after passing a leaf
while (cur != null) {
// The target is in the right subtree of cur
cur = if (cur._val < num)
cur.right
// The target is in the left subtree of cur
else if (cur._val > num)
cur.left
// The target was found, so exit the loop
else
break
}
// Return the target node
return cur
}
### Search for a node ###
def search(num)
cur = @root
# Stop the search after passing a leaf
while !cur.nil?
# The target is in the right subtree of cur
if cur.val < num
cur = cur.right
# The target is in the left subtree of cur
elsif cur.val > num
cur = cur.left
# The target was found, so exit the loop
else
break
end
end
cur
end
Visualize execution
2. Insert a node¶
To insert a value num while preserving the ordering “left subtree < root < right subtree,” follow the steps shown below.
- Find the insertion position. As in a search, start at the root and compare each node's value with
numto decide which way to go. Stop when you pass a leaf and reachNone. - Insert the node at that position. Create a node with value
numand put it in the position occupied byNone.
Figure 7-18 Inserting a node into a binary search tree
Description of Figure 7-18: Inserting a node into a binary search tree
Compare values on the way down until you reach a null reference. Use the parent pointer pre to attach the new leaf to the tree.
The binary search trees in this book do not store duplicates. At every node, all values in its left subtree are smaller than its value, and all values in its right subtree are larger.
Insert 16 into the tree rooted at 8 that contains values 1 through 15. The figure shows the tree before and after insertion, and the table compares the connections side by side. “Empty” means there is no child. “Not yet added” means the node did not exist at that stage.
| Node | Left child before insertion | Right child before insertion | Left child after insertion | Right child after insertion |
|---|---|---|---|---|
| 1 | Empty | Empty | Empty | Empty |
| 2 | 1 | 3 | 1 | 3 |
| 3 | Empty | Empty | Empty | Empty |
| 4 | 2 | 6 | 2 | 6 |
| 5 | Empty | Empty | Empty | Empty |
| 6 | 5 | 7 | 5 | 7 |
| 7 | Empty | Empty | Empty | Empty |
| 8 | 4 | 12 | 4 | 12 |
| 9 | Empty | Empty | Empty | Empty |
| 10 | 9 | 11 | 9 | 11 |
| 11 | Empty | Empty | Empty | Empty |
| 12 | 10 | 14 | 10 | 14 |
| 13 | Empty | Empty | Empty | Empty |
| 14 | 13 | 15 | 13 | 15 |
| 15 | Empty | Empty | Empty | 16 |
| 16 | Not yet added | Not yet added | Empty | Empty |
The value 16 is greater than each of 8, 12, 14, and 15. Follow right links through these four nodes until cur reaches the empty position None. The last non-null node, 15, is saved in pre. Create node 16 and set pre.right to the new node, making it the right child of 15.
After insertion, the tree contains values 1 through 16 and still satisfies the search ordering. Once cur becomes None, it cannot lead back to the parent, so pre must retain a reference to the last non-null node.
Keep two points in mind when implementing insertion.
- Duplicate values would violate our definition of a binary search tree. If the value is already in the tree, return without inserting a node.
- Use
preto remember the node from the previous iteration. When you reachNone, you will still have the parent reference you need to attach the new node.
def insert(self, num: int):
"""Insert a node"""
# If the tree is empty, initialize the root
if self._root is None:
self._root = TreeNode(num)
return
# Stop the search after passing a leaf
cur, pre = self._root, None
while cur is not None:
# Return if a duplicate is found
if cur.val == num:
return
pre = cur
# The insertion position is in the right subtree of cur
if cur.val < num:
cur = cur.right
# The insertion position is in the left subtree of cur
else:
cur = cur.left
# Insert a node
node = TreeNode(num)
if pre.val < num:
pre.right = node
else:
pre.left = node
/* Insert a node */
void insert(int num) {
// If the tree is empty, initialize the root
if (root == nullptr) {
root = new TreeNode(num);
return;
}
TreeNode *cur = root, *pre = nullptr;
// Stop the search after passing a leaf
while (cur != nullptr) {
// Return if a duplicate is found
if (cur->val == num)
return;
pre = cur;
// The insertion position is in the right subtree of cur
if (cur->val < num)
cur = cur->right;
// The insertion position is in the left subtree of cur
else
cur = cur->left;
}
// Insert a node
TreeNode *node = new TreeNode(num);
if (pre->val < num)
pre->right = node;
else
pre->left = node;
}
/* Insert a node */
void insert(int num) {
// If the tree is empty, initialize the root
if (root == null) {
root = new TreeNode(num);
return;
}
TreeNode cur = root, pre = null;
// Stop the search after passing a leaf
while (cur != null) {
// Return if a duplicate is found
if (cur.val == num)
return;
pre = cur;
// The insertion position is in the right subtree of cur
if (cur.val < num)
cur = cur.right;
// The insertion position is in the left subtree of cur
else
cur = cur.left;
}
// Insert a node
TreeNode node = new TreeNode(num);
if (pre.val < num)
pre.right = node;
else
pre.left = node;
}
/* Insert a node */
void Insert(int num) {
// If the tree is empty, initialize the root
if (root == null) {
root = new TreeNode(num);
return;
}
TreeNode? cur = root, pre = null;
// Stop the search after passing a leaf
while (cur != null) {
// Return if a duplicate is found
if (cur.val == num)
return;
pre = cur;
// The insertion position is in the right subtree of cur
if (cur.val < num)
cur = cur.right;
// The insertion position is in the left subtree of cur
else
cur = cur.left;
}
// Insert a node
TreeNode node = new(num);
if (pre != null) {
if (pre.val < num)
pre.right = node;
else
pre.left = node;
}
}
/* Insert a node */
func (bst *binarySearchTree) insert(num int) {
cur := bst.root
// If the tree is empty, initialize the root
if cur == nil {
bst.root = NewTreeNode(num)
return
}
// Track the parent of the node to insert
var pre *TreeNode = nil
// Stop the search after passing a leaf
for cur != nil {
if cur.Val == num {
return
}
pre = cur
if cur.Val.(int) < num {
cur = cur.Right
} else {
cur = cur.Left
}
}
// Insert a node
node := NewTreeNode(num)
if pre.Val.(int) < num {
pre.Right = node
} else {
pre.Left = node
}
}
/* Insert a node */
func insert(num: Int) {
// If the tree is empty, initialize the root
if root == nil {
root = TreeNode(x: num)
return
}
var cur = root
var pre: TreeNode?
// Stop the search after passing a leaf
while cur != nil {
// Return if a duplicate is found
if cur!.val == num {
return
}
pre = cur
// The insertion position is in the right subtree of cur
if cur!.val < num {
cur = cur?.right
}
// The insertion position is in the left subtree of cur
else {
cur = cur?.left
}
}
// Insert a node
let node = TreeNode(x: num)
if pre!.val < num {
pre?.right = node
} else {
pre?.left = node
}
}
/* Insert a node */
insert(num) {
// If the tree is empty, initialize the root
if (this.root === null) {
this.root = new TreeNode(num);
return;
}
let cur = this.root,
pre = null;
// Stop the search after passing a leaf
while (cur !== null) {
// Return if a duplicate is found
if (cur.val === num) return;
pre = cur;
// The insertion position is in the right subtree of cur
if (cur.val < num) cur = cur.right;
// The insertion position is in the left subtree of cur
else cur = cur.left;
}
// Insert a node
const node = new TreeNode(num);
if (pre.val < num) pre.right = node;
else pre.left = node;
}
/* Insert a node */
insert(num: number): void {
// If the tree is empty, initialize the root
if (this.root === null) {
this.root = new TreeNode(num);
return;
}
let cur: TreeNode | null = this.root,
pre: TreeNode | null = null;
// Stop the search after passing a leaf
while (cur !== null) {
// Return if a duplicate is found
if (cur.val === num) return;
pre = cur;
// The insertion position is in the right subtree of cur
if (cur.val < num) cur = cur.right;
// The insertion position is in the left subtree of cur
else cur = cur.left;
}
// Insert a node
const node = new TreeNode(num);
if (pre!.val < num) pre!.right = node;
else pre!.left = node;
}
/* Insert a node */
void insert(int _num) {
// If the tree is empty, initialize the root
if (_root == null) {
_root = TreeNode(_num);
return;
}
TreeNode? cur = _root;
TreeNode? pre = null;
// Stop the search after passing a leaf
while (cur != null) {
// Return if a duplicate is found
if (cur.val == _num) return;
pre = cur;
// The insertion position is in the right subtree of cur
if (cur.val < _num)
cur = cur.right;
// The insertion position is in the left subtree of cur
else
cur = cur.left;
}
// Insert a node
TreeNode? node = TreeNode(_num);
if (pre!.val < _num)
pre.right = node;
else
pre.left = node;
}
/* Insert a node */
pub fn insert(&mut self, num: i32) {
// If the tree is empty, initialize the root
if self.root.is_none() {
self.root = Some(TreeNode::new(num));
return;
}
let mut cur = self.root.clone();
let mut pre = None;
// Stop the search after passing a leaf
while let Some(node) = cur.clone() {
match num.cmp(&node.borrow().val) {
// Return if a duplicate is found
Ordering::Equal => return,
// The insertion position is in the right subtree of cur
Ordering::Greater => {
pre = cur.clone();
cur = node.borrow().right.clone();
}
// The insertion position is in the left subtree of cur
Ordering::Less => {
pre = cur.clone();
cur = node.borrow().left.clone();
}
}
}
// Insert a node
let pre = pre.unwrap();
let node = Some(TreeNode::new(num));
if num > pre.borrow().val {
pre.borrow_mut().right = node;
} else {
pre.borrow_mut().left = node;
}
}
/* Insert a node */
void insert(BinarySearchTree *bst, int num) {
// If the tree is empty, initialize the root
if (bst->root == NULL) {
bst->root = newTreeNode(num);
return;
}
TreeNode *cur = bst->root, *pre = NULL;
// Stop the search after passing a leaf
while (cur != NULL) {
// Return if a duplicate is found
if (cur->val == num) {
return;
}
pre = cur;
if (cur->val < num) {
// The insertion position is in the right subtree of cur
cur = cur->right;
} else {
// The insertion position is in the left subtree of cur
cur = cur->left;
}
}
// Insert a node
TreeNode *node = newTreeNode(num);
if (pre->val < num) {
pre->right = node;
} else {
pre->left = node;
}
}
/* Insert a node */
fun insert(num: Int) {
// If the tree is empty, initialize the root
if (root == null) {
root = TreeNode(num)
return
}
var cur = root
var pre: TreeNode? = null
// Stop the search after passing a leaf
while (cur != null) {
// Return if a duplicate is found
if (cur._val == num)
return
pre = cur
// The insertion position is in the right subtree of cur
cur = if (cur._val < num)
cur.right
// The insertion position is in the left subtree of cur
else
cur.left
}
// Insert a node
val node = TreeNode(num)
if (pre?._val!! < num)
pre.right = node
else
pre.left = node
}
### Insert a node ###
def insert(num)
# If the tree is empty, initialize the root
if @root.nil?
@root = TreeNode.new(num)
return
end
# Stop the search after passing a leaf
cur, pre = @root, nil
while !cur.nil?
# Return if a duplicate is found
return if cur.val == num
pre = cur
# The insertion position is in the right subtree of cur
if cur.val < num
cur = cur.right
# The insertion position is in the left subtree of cur
else
cur = cur.left
end
end
# Insert a node
node = TreeNode.new(num)
if pre.val < num
pre.right = node
else
pre.left = node
end
end
Visualize execution
Like search, insertion takes \(O(\log n)\) time.
3. Delete a node¶
First find the target in the binary tree, then delete it. As with insertion, deletion must preserve the ordering “left subtree < root < right subtree.” How we delete the target depends on whether it has zero, one, or two children.
As shown below, a node of degree \(0\) is a leaf and can be deleted directly.
Figure 7-19 Deleting a node of degree 0 from a binary search tree
Description of Figure 7-19: Deleting a leaf from a binary search tree
A leaf has degree 0, so there is no subtree to reconnect. Simply clear the parent's reference to the leaf.
Delete leaf 1 from the tree rooted at 8 that contains values 1 through 15. Between the before and after panels, the figure notes that the node has degree 0. The pointer cur identifies the target, and pre identifies its parent. The table compares connections before and after deletion. “Removed” means the node no longer belongs to the tree.
| Node | Left child before deletion | Right child before deletion | Left child after deletion | Right child after deletion |
|---|---|---|---|---|
| 1 | Empty | Empty | Removed | Removed |
| 2 | 1 | 3 | Empty | 3 |
| 3 | Empty | Empty | Empty | Empty |
| 4 | 2 | 6 | 2 | 6 |
| 5 | Empty | Empty | Empty | Empty |
| 6 | 5 | 7 | 5 | 7 |
| 7 | Empty | Empty | Empty | Empty |
| 8 | 4 | 12 | 4 | 12 |
| 9 | Empty | Empty | Empty | Empty |
| 10 | 9 | 11 | 9 | 11 |
| 11 | Empty | Empty | Empty | Empty |
| 12 | 10 | 14 | 10 | 14 |
| 13 | Empty | Empty | Empty | Empty |
| 14 | 13 | 15 | 13 | 15 |
| 15 | Empty | Empty | Empty | Empty |
To delete 1, follow 8 → 4 → 2 → 1 from the root. Now cur points to 1 and pre points to its parent, 2. Node 1 has no children, so its degree is 0 and there is no subtree to reconnect. Set pre.left = None to clear parent 2's left reference.
Values 2 through 15 remain in binary search tree order. The empty position to the left of 2 represents a None reference, not a new node.
As shown below, a node of degree \(1\) can simply be replaced by its only child.
Figure 7-20 Deleting a node of degree 1 from a binary search tree
Description of Figure 7-20: Deleting a node with one child from a binary search tree
To delete a node of degree 1, redirect its parent's reference from the target to the target's only child.
Delete node 2 from the tree rooted at 8 that contains values 2 through 15. The initial state matches Figure 7-19 after node 1 was deleted: node 2 has only a right child, 3. The figure shows the deletion with before and after panels and a note identifying degree 1. The table compares the connections. “Removed” means the node no longer belongs to the tree.
| Node | Left child before deletion | Right child before deletion | Left child after deletion | Right child after deletion |
|---|---|---|---|---|
| 2 | Empty | 3 | Removed | Removed |
| 3 | Empty | Empty | Empty | Empty |
| 4 | 2 | 6 | 3 | 6 |
| 5 | Empty | Empty | Empty | Empty |
| 6 | 5 | 7 | 5 | 7 |
| 7 | Empty | Empty | Empty | Empty |
| 8 | 4 | 12 | 4 | 12 |
| 9 | Empty | Empty | Empty | Empty |
| 10 | 9 | 11 | 9 | 11 |
| 11 | Empty | Empty | Empty | Empty |
| 12 | 10 | 14 | 10 | 14 |
| 13 | Empty | Empty | Empty | Empty |
| 14 | 13 | 15 | 13 | 15 |
| 15 | Empty | Empty | Empty | Empty |
To delete 2, follow 8 → 4 → 2 to find cur = 2 and its parent pre = 4. Node 2 has no left child and has right child 3, so its degree is 1. Simply clearing 4.left as for a leaf would disconnect node 3 from the root even though it must be retained. Instead, set pre.left = cur.right so that 4.left points to 3.
After deletion, values 3 through 15 remain in search tree order. The operation changes a parent-child reference. Node 3 keeps its identity and becomes the left child of 4. The value of node 2 is never overwritten.
We cannot simply remove a node of degree \(2\). We need a replacement. To preserve the ordering “left subtree \(<\) root \(<\) right subtree,” we can use either the smallest node in the right subtree or the largest node in the left subtree.
Suppose we choose the smallest node in the right subtree, which comes next in inorder traversal. Figure 7-21 shows the deletion.
- Find the node immediately after the target in the inorder sequence and call it
tmp. - Use the value of
tmpto overwrite the target's value, and recursively delete nodetmpfrom the tree.
Figure 7-21 Deleting a node of degree 2 from a binary search tree
Description of Figure 7-21: Deleting a node with two children from a binary search tree
To delete a node of degree 2, first locate and detach its inorder successor in the right subtree. Then write the successor's value into the target node cur.
The value to delete is 4. The initial tree contains values 3 through 15 and has root 8. The table lists all initial connections. “Empty” means there is no child. The pointer cur always refers to the object that originally held 4.
Steps 1 and 2 leave the connections unchanged. Step 3 detaches the original node 5. Only in step 4 is the value 5 written into cur. Except for the changes specified at each step, the table's connections stay the same. The right subtree rooted at 12 stays intact throughout. The successor pointer nex in the figure corresponds to tmp in the code.
The figure follows the code: recursively delete the successor first, then overwrite the value of cur. If cur were changed to 5 first, a search from the root to delete the value 5 would hit cur first. The two steps in this code cannot simply be swapped.
| Node | Initial left child | Initial right child |
|---|---|---|
| 8 (root) | cur (initial value 4) | 12 |
| 3 | Empty | Empty |
| cur (initial value 4) | 3 | 6 |
| 5 (original node) | Empty | Empty |
| 6 | 5 (original node) | 7 |
| 7 | Empty | Empty |
| 9 | Empty | Empty |
| 10 | 9 | 11 |
| 11 | Empty | Empty |
| 12 | 10 | 14 |
| 13 | Empty | Empty |
| 14 | 13 | 15 |
| 15 | Empty | Empty |
Locate the target with two children
The target value 4 is less than root 8, so go left to find cur (currently 4). Its left child is 3 and its right child is 6. Node 6 has left leaf 5 and right leaf 7, as shown in “Connections throughout the tree before deletion.” Since cur has degree 2, we cannot simply cut its parent edge. Here we use the minimum value in its right subtree as a replacement.
Find the inorder successor, 5
Follow cur (4) → 6 → 5 to the inorder successor and point nex to the original node 5. Root 8 still has left child cur, cur has left child 3 and right child 6, and 6 has left child 5 and right child 7. No value or connection has changed. As the minimum in the right subtree, 5 is larger than 3 on the left and smaller than the remaining values 6 and 7 on the right, so the replacement preserves the search ordering.
Detach the original successor node
Recursively delete leaf 5, referenced by nex, by clearing 6.left. Root 8 has left child cur (still holding 4). The left and right children of cur are 3 and 6. Node 6 has no left child and has right leaf 7. Only the original node 5 has been detached. All other connections still match the initial table. The pointer nex retains a reference to the original node so its value can be read in the next step. The dashed circle marks its old position for comparison. It is no longer a node in the tree.
Write the successor's value into cur
Write the successor's value 5 into cur, overwriting 4. Root 8 has left child cur (now holding 5), and cur has left child 3 and right child 6. Node 6 has no left child and has right leaf 7. Only the value of cur has changed. Its links to parent 8 and children 3 and 6 stay the same. The original node 5 has been detached, leaving exactly one value 5 in the tree.
When deletion is complete, the tree no longer contains the value 4. The cur object remains in place, and the other nodes and the search ordering are preserved.
Deletion also takes \(O(\log n)\) time. Finding the target takes \(O(\log n)\) time, and finding its inorder successor takes \(O(\log n)\) time. Here is an implementation:
def remove(self, num: int):
"""Delete a node"""
# Return immediately if the tree is empty
if self._root is None:
return
# Stop the search after passing a leaf
cur, pre = self._root, None
while cur is not None:
# The node to delete was found, so exit the loop
if cur.val == num:
break
pre = cur
# The node to delete is in the right subtree of cur
if cur.val < num:
cur = cur.right
# The node to delete is in the left subtree of cur
else:
cur = cur.left
# Return if the node to delete does not exist
if cur is None:
return
# Number of children = 0 or 1
if cur.left is None or cur.right is None:
# With no children, child = null. With one child, child is that child.
child = cur.left or cur.right
# Delete node cur
if cur != self._root:
if pre.left == cur:
pre.left = child
else:
pre.right = child
else:
# If deleting the root, assign a new root
self._root = child
# Number of children = 2
else:
# Get the inorder successor of cur
tmp: TreeNode = cur.right
while tmp.left is not None:
tmp = tmp.left
# Recursively delete node tmp
self.remove(tmp.val)
# Replace the value of cur with that of tmp
cur.val = tmp.val
/* Delete a node */
void remove(int num) {
// Return immediately if the tree is empty
if (root == nullptr)
return;
TreeNode *cur = root, *pre = nullptr;
// Stop the search after passing a leaf
while (cur != nullptr) {
// The node to delete was found, so exit the loop
if (cur->val == num)
break;
pre = cur;
// The node to delete is in the right subtree of cur
if (cur->val < num)
cur = cur->right;
// The node to delete is in the left subtree of cur
else
cur = cur->left;
}
// Return if the node to delete does not exist
if (cur == nullptr)
return;
// Number of children = 0 or 1
if (cur->left == nullptr || cur->right == nullptr) {
// With no children, child = nullptr. With one child, child is that child.
TreeNode *child = cur->left != nullptr ? cur->left : cur->right;
// Delete node cur
if (cur != root) {
if (pre->left == cur)
pre->left = child;
else
pre->right = child;
} else {
// If deleting the root, assign a new root
root = child;
}
// Free memory
delete cur;
}
// Number of children = 2
else {
// Get the inorder successor of cur
TreeNode *tmp = cur->right;
while (tmp->left != nullptr) {
tmp = tmp->left;
}
int tmpVal = tmp->val;
// Recursively delete node tmp
remove(tmp->val);
// Replace the value of cur with that of tmp
cur->val = tmpVal;
}
}
/* Delete a node */
void remove(int num) {
// Return immediately if the tree is empty
if (root == null)
return;
TreeNode cur = root, pre = null;
// Stop the search after passing a leaf
while (cur != null) {
// The node to delete was found, so exit the loop
if (cur.val == num)
break;
pre = cur;
// The node to delete is in the right subtree of cur
if (cur.val < num)
cur = cur.right;
// The node to delete is in the left subtree of cur
else
cur = cur.left;
}
// Return if the node to delete does not exist
if (cur == null)
return;
// Number of children = 0 or 1
if (cur.left == null || cur.right == null) {
// With no children, child = null. With one child, child is that child.
TreeNode child = cur.left != null ? cur.left : cur.right;
// Delete node cur
if (cur != root) {
if (pre.left == cur)
pre.left = child;
else
pre.right = child;
} else {
// If deleting the root, assign a new root
root = child;
}
}
// Number of children = 2
else {
// Get the inorder successor of cur
TreeNode tmp = cur.right;
while (tmp.left != null) {
tmp = tmp.left;
}
// Recursively delete node tmp
remove(tmp.val);
// Replace the value of cur with that of tmp
cur.val = tmp.val;
}
}
/* Delete a node */
void Remove(int num) {
// Return immediately if the tree is empty
if (root == null)
return;
TreeNode? cur = root, pre = null;
// Stop the search after passing a leaf
while (cur != null) {
// The node to delete was found, so exit the loop
if (cur.val == num)
break;
pre = cur;
// The node to delete is in the right subtree of cur
if (cur.val < num)
cur = cur.right;
// The node to delete is in the left subtree of cur
else
cur = cur.left;
}
// Return if the node to delete does not exist
if (cur == null)
return;
// Number of children = 0 or 1
if (cur.left == null || cur.right == null) {
// With no children, child = null. With one child, child is that child.
TreeNode? child = cur.left ?? cur.right;
// Delete node cur
if (cur != root) {
if (pre!.left == cur)
pre.left = child;
else
pre.right = child;
} else {
// If deleting the root, assign a new root
root = child;
}
}
// Number of children = 2
else {
// Get the inorder successor of cur
TreeNode? tmp = cur.right;
while (tmp.left != null) {
tmp = tmp.left;
}
// Recursively delete node tmp
Remove(tmp.val!.Value);
// Replace the value of cur with that of tmp
cur.val = tmp.val;
}
}
/* Delete a node */
func (bst *binarySearchTree) remove(num int) {
cur := bst.root
// Return immediately if the tree is empty
if cur == nil {
return
}
// Track the parent of the node to delete
var pre *TreeNode = nil
// Stop the search after passing a leaf
for cur != nil {
if cur.Val == num {
break
}
pre = cur
if cur.Val.(int) < num {
// The node to delete is in the right subtree
cur = cur.Right
} else {
// The node to delete is in the left subtree
cur = cur.Left
}
}
// Return if the node to delete does not exist
if cur == nil {
return
}
// Zero or one child
if cur.Left == nil || cur.Right == nil {
var child *TreeNode = nil
// Get the child of the node to delete
if cur.Left != nil {
child = cur.Left
} else {
child = cur.Right
}
// Delete node cur
if cur != bst.root {
if pre.Left == cur {
pre.Left = child
} else {
pre.Right = child
}
} else {
// If deleting the root, assign a new root
bst.root = child
}
// Two children
} else {
// Get the inorder successor of the node cur to be deleted
tmp := cur.Right
for tmp.Left != nil {
tmp = tmp.Left
}
// Recursively delete node tmp
bst.remove(tmp.Val.(int))
// Replace the value of cur with that of tmp
cur.Val = tmp.Val
}
}
/* Delete a node */
func remove(num: Int) {
// Return immediately if the tree is empty
if root == nil {
return
}
var cur = root
var pre: TreeNode?
// Stop the search after passing a leaf
while cur != nil {
// The node to delete was found, so exit the loop
if cur!.val == num {
break
}
pre = cur
// The node to delete is in the right subtree of cur
if cur!.val < num {
cur = cur?.right
}
// The node to delete is in the left subtree of cur
else {
cur = cur?.left
}
}
// Return if the node to delete does not exist
if cur == nil {
return
}
// Number of children = 0 or 1
if cur?.left == nil || cur?.right == nil {
// With no children, child = null. With one child, child is that child.
let child = cur?.left ?? cur?.right
// Delete node cur
if cur !== root {
if pre?.left === cur {
pre?.left = child
} else {
pre?.right = child
}
} else {
// If deleting the root, assign a new root
root = child
}
}
// Number of children = 2
else {
// Get the inorder successor of cur
var tmp = cur?.right
while tmp?.left != nil {
tmp = tmp?.left
}
// Recursively delete node tmp
remove(num: tmp!.val)
// Replace the value of cur with that of tmp
cur?.val = tmp!.val
}
}
/* Delete a node */
remove(num) {
// Return immediately if the tree is empty
if (this.root === null) return;
let cur = this.root,
pre = null;
// Stop the search after passing a leaf
while (cur !== null) {
// The node to delete was found, so exit the loop
if (cur.val === num) break;
pre = cur;
// The node to delete is in the right subtree of cur
if (cur.val < num) cur = cur.right;
// The node to delete is in the left subtree of cur
else cur = cur.left;
}
// Return if the node to delete does not exist
if (cur === null) return;
// Number of children = 0 or 1
if (cur.left === null || cur.right === null) {
// With no children, child = null. With one child, child is that child.
const child = cur.left !== null ? cur.left : cur.right;
// Delete node cur
if (cur !== this.root) {
if (pre.left === cur) pre.left = child;
else pre.right = child;
} else {
// If deleting the root, assign a new root
this.root = child;
}
}
// Number of children = 2
else {
// Get the inorder successor of cur
let tmp = cur.right;
while (tmp.left !== null) {
tmp = tmp.left;
}
// Recursively delete node tmp
this.remove(tmp.val);
// Replace the value of cur with that of tmp
cur.val = tmp.val;
}
}
/* Delete a node */
remove(num: number): void {
// Return immediately if the tree is empty
if (this.root === null) return;
let cur: TreeNode | null = this.root,
pre: TreeNode | null = null;
// Stop the search after passing a leaf
while (cur !== null) {
// The node to delete was found, so exit the loop
if (cur.val === num) break;
pre = cur;
// The node to delete is in the right subtree of cur
if (cur.val < num) cur = cur.right;
// The node to delete is in the left subtree of cur
else cur = cur.left;
}
// Return if the node to delete does not exist
if (cur === null) return;
// Number of children = 0 or 1
if (cur.left === null || cur.right === null) {
// With no children, child = null. With one child, child is that child.
const child: TreeNode | null =
cur.left !== null ? cur.left : cur.right;
// Delete node cur
if (cur !== this.root) {
if (pre!.left === cur) pre!.left = child;
else pre!.right = child;
} else {
// If deleting the root, assign a new root
this.root = child;
}
}
// Number of children = 2
else {
// Get the inorder successor of cur
let tmp: TreeNode | null = cur.right;
while (tmp!.left !== null) {
tmp = tmp!.left;
}
// Recursively delete node tmp
this.remove(tmp!.val);
// Replace the value of cur with that of tmp
cur.val = tmp!.val;
}
}
/* Delete a node */
void remove(int _num) {
// Return immediately if the tree is empty
if (_root == null) return;
TreeNode? cur = _root;
TreeNode? pre = null;
// Stop the search after passing a leaf
while (cur != null) {
// The node to delete was found, so exit the loop
if (cur.val == _num) break;
pre = cur;
// The node to delete is in the right subtree of cur
if (cur.val < _num)
cur = cur.right;
// The node to delete is in the left subtree of cur
else
cur = cur.left;
}
// Return if the node to delete does not exist
if (cur == null) return;
// Number of children = 0 or 1
if (cur.left == null || cur.right == null) {
// With no children, child = null. With one child, child is that child.
TreeNode? child = cur.left ?? cur.right;
// Delete node cur
if (cur != _root) {
if (pre!.left == cur)
pre.left = child;
else
pre.right = child;
} else {
// If deleting the root, assign a new root
_root = child;
}
} else {
// Number of children = 2
// Get the inorder successor of cur
TreeNode? tmp = cur.right;
while (tmp!.left != null) {
tmp = tmp.left;
}
// Recursively delete node tmp
remove(tmp.val);
// Replace the value of cur with that of tmp
cur.val = tmp.val;
}
}
/* Delete a node */
pub fn remove(&mut self, num: i32) {
// Return immediately if the tree is empty
if self.root.is_none() {
return;
}
let mut cur = self.root.clone();
let mut pre = None;
// Stop the search after passing a leaf
while let Some(node) = cur.clone() {
match num.cmp(&node.borrow().val) {
// The node to delete was found, so exit the loop
Ordering::Equal => break,
// The node to delete is in the right subtree of cur
Ordering::Greater => {
pre = cur.clone();
cur = node.borrow().right.clone();
}
// The node to delete is in the left subtree of cur
Ordering::Less => {
pre = cur.clone();
cur = node.borrow().left.clone();
}
}
}
// Return if the node to delete does not exist
if cur.is_none() {
return;
}
let cur = cur.unwrap();
let (left_child, right_child) = (cur.borrow().left.clone(), cur.borrow().right.clone());
match (left_child.clone(), right_child.clone()) {
// Number of children = 0 or 1
(None, None) | (Some(_), None) | (None, Some(_)) => {
// With no children, child = nullptr. With one child, child is that child.
let child = left_child.or(right_child);
// Delete node cur
if !Rc::ptr_eq(&cur, self.root.as_ref().unwrap()) {
let pre = pre.unwrap();
let left = pre.borrow().left.clone();
if left.is_some() && Rc::ptr_eq(left.as_ref().unwrap(), &cur) {
pre.borrow_mut().left = child;
} else {
pre.borrow_mut().right = child;
}
} else {
// If deleting the root, assign a new root
self.root = child;
}
}
// Number of children = 2
(Some(_), Some(_)) => {
// Get the inorder successor of cur
let mut tmp = cur.borrow().right.clone();
while let Some(node) = tmp.clone() {
if node.borrow().left.is_some() {
tmp = node.borrow().left.clone();
} else {
break;
}
}
let tmp_val = tmp.unwrap().borrow().val;
// Recursively delete node tmp
self.remove(tmp_val);
// Replace the value of cur with that of tmp
cur.borrow_mut().val = tmp_val;
}
}
}
/* Delete a node */
// Including stdio.h prevents us from using the name remove here
void removeItem(BinarySearchTree *bst, int num) {
// Return immediately if the tree is empty
if (bst->root == NULL)
return;
TreeNode *cur = bst->root, *pre = NULL;
// Stop the search after passing a leaf
while (cur != NULL) {
// The node to delete was found, so exit the loop
if (cur->val == num)
break;
pre = cur;
if (cur->val < num) {
// The node to delete is in the right subtree of root
cur = cur->right;
} else {
// The node to delete is in the left subtree of root
cur = cur->left;
}
}
// Return if the node to delete does not exist
if (cur == NULL)
return;
// Check whether the node to delete has children
if (cur->left == NULL || cur->right == NULL) {
/* Number of children = 0 or 1 */
// With no children, child = nullptr. With one child, child is that child.
TreeNode *child = cur->left != NULL ? cur->left : cur->right;
// Delete node cur
if (pre == NULL) {
bst->root = child;
} else if (pre->left == cur) {
pre->left = child;
} else {
pre->right = child;
}
// Free memory
free(cur);
} else {
/* Number of children = 2 */
// Get the inorder successor of cur
TreeNode *tmp = cur->right;
while (tmp->left != NULL) {
tmp = tmp->left;
}
int tmpVal = tmp->val;
// Recursively delete node tmp
removeItem(bst, tmp->val);
// Replace the value of cur with that of tmp
cur->val = tmpVal;
}
}
/* Delete a node */
fun remove(num: Int) {
// Return immediately if the tree is empty
if (root == null)
return
var cur = root
var pre: TreeNode? = null
// Stop the search after passing a leaf
while (cur != null) {
// The node to delete was found, so exit the loop
if (cur._val == num)
break
pre = cur
// The node to delete is in the right subtree of cur
cur = if (cur._val < num)
cur.right
// The node to delete is in the left subtree of cur
else
cur.left
}
// Return if the node to delete does not exist
if (cur == null)
return
// Number of children = 0 or 1
if (cur.left == null || cur.right == null) {
// With no children, child = null. With one child, child is that child.
val child = if (cur.left != null)
cur.left
else
cur.right
// Delete node cur
if (cur != root) {
if (pre!!.left == cur)
pre.left = child
else
pre.right = child
} else {
// If deleting the root, assign a new root
root = child
}
// Number of children = 2
} else {
// Get the inorder successor of cur
var tmp = cur.right
while (tmp!!.left != null) {
tmp = tmp.left
}
// Recursively delete node tmp
remove(tmp._val)
// Replace the value of cur with that of tmp
cur._val = tmp._val
}
}
### Delete a node ###
def remove(num)
# Return immediately if the tree is empty
return if @root.nil?
# Stop the search after passing a leaf
cur, pre = @root, nil
while !cur.nil?
# The node to delete was found, so exit the loop
break if cur.val == num
pre = cur
# The node to delete is in the right subtree of cur
if cur.val < num
cur = cur.right
# The node to delete is in the left subtree of cur
else
cur = cur.left
end
end
# Return if the node to delete does not exist
return if cur.nil?
# Number of children = 0 or 1
if cur.left.nil? || cur.right.nil?
# With no children, child = null. With one child, child is that child.
child = cur.left || cur.right
# Delete node cur
if cur != @root
if pre.left == cur
pre.left = child
else
pre.right = child
end
else
# If deleting the root, assign a new root
@root = child
end
# Number of children = 2
else
# Get the inorder successor of cur
tmp = cur.right
while !tmp.left.nil?
tmp = tmp.left
end
# Recursively delete node tmp
remove(tmp.val)
# Replace the value of cur with that of tmp
cur.val = tmp.val
end
end
Visualize execution
4. Inorder traversal yields sorted values¶
As Figure 7-22 shows, inorder traversal visits a binary tree in the order “left \(\rightarrow\) root \(\rightarrow\) right,” while a binary search tree satisfies “left child \(<\) root \(<\) right child.”
An inorder traversal of a binary search tree therefore always visits the next smallest node. This gives us an important property: the inorder sequence of a binary search tree is in ascending order.
This property lets us obtain sorted data from a binary search tree in just \(O(n)\) time, without a separate sorting step.
Figure 7-22 Inorder sequence of a binary search tree
Description of Figure 7-22: Inorder traversal of a binary search tree
An inorder traversal visits the left subtree, the current node, and then the right subtree, yielding all the values of a binary search tree directly in ascending order.
The binary search trees in this book do not store duplicates. At every node, all values in its left subtree are smaller than its value, and all values in its right subtree are larger.
The input tree has root 8 with left child 4 and right child 12. Node 4 has left child 2 and right child 6, and 12 has left child 10 and right child 14. Nodes 2, 6, 10, and 14 are leaves. A dashed green path traces the traversal, and blue dots show when each node is recorded.
At each node, recursively visit its left subtree of smaller values, record the node itself, then visit its right subtree of larger values. The left subtree of root 8 yields 2, 4, and 6. Next comes 8, then the right subtree yields 10, 12, and 14. The full result on the right is [2, 4, 6, 8, 10, 12, 14].
Inorder traversal yields ascending values without a separate sort. The sequence is strictly increasing because this book's definition excludes duplicate node values.
7.4.2 Efficiency of binary search trees¶
Suppose we want to store a collection of values in either an array or a binary search tree. In Table 7-2, the search tree operations all take logarithmic time, giving consistent, efficient performance. An array is more efficient only when additions are frequent and searches and deletions are infrequent.
Table 7-2 Efficiency of arrays and search trees
| Unsorted array | Binary search tree | |
|---|---|---|
| Find an element | \(O(n)\) | \(O(\log n)\) |
| Insert an element | \(O(1)\) | \(O(\log n)\) |
| Delete an element | \(O(n)\) | \(O(\log n)\) |
Ideally, a binary search tree is balanced, so we can find any node within \(\log n\) iterations.
Repeated insertions and deletions, however, can turn a binary search tree into a linked list, as shown below. The time complexity of its operations then worsens to \(O(n)\).
Figure 7-23 A binary search tree degenerates into a chain
Description of Figure 7-23: Balanced and chain-shaped binary search trees
Two trees with the same seven nodes can both satisfy the search ordering yet have different search path lengths because of their shapes.
For each node in a binary search tree, every value in its left subtree must be smaller than its own and every value in its right subtree must be larger. The arrows point from parent to child.
The left diagram, labeled “Balanced binary search tree,” has root 4 with left child 2 and right child 6. Node 2 has left child 1 and right child 3, and 6 has left child 5 and right child 7. The tree has three levels and a height of 2 edges. The right diagram, labeled “Degenerate binary search tree,” has root 7. Following left child pointers gives the chain 7 → 6 → 5 → 4 → 3 → 2 → 1. Every right child is empty. The tree has seven levels and a height of 6 edges.
Both trees contain exactly the values 1 through 7 and strictly satisfy the binary search tree ordering: smaller on the left, larger on the right. Trace a search for leaf 1. The left tree needs only three comparisons along 4 → 2 → 1. The right tree must compare all seven nodes along 7 → 6 → 5 → 4 → 3 → 2 → 1. The figure compares two fixed structures. It does not show a sequence of insertions or deletions turning one into the other.
When a binary search tree stays balanced, search, insertion, and deletion take logarithmic time. If it degenerates into a one-sided chain, the worst case visits every node and takes O(n) time.
7.4.3 Common applications of binary search trees¶
- Multilevel indexes that support efficient searches, insertions, and deletions.
- The underlying data structure for certain search algorithms.
- Storing streaming data in sorted order.