algoritmauzmanı
Sign in
TREN
6.4Binary Search Tree with an Array
Lesson 6.4.3

Insert: finding the empty place

Adding a new value to a starts with searching for that value. If it is not in the tree, the search ends at an empty cell, and that cell is the only place where the value can sit without breaking the BST rule. The value is written there and becomes a new of the tree.

What you will learn
  • How the search path finds the place for a new value
  • Why a new value is always a leaf
  • The two cases where insertion fails
5 minTime O(h)Memory O(1)C · Java · Python

1Idea

The loop is the same as the search loop: start at i = 0, go to 2i+1 if the value is smaller and to 2i+2 if it is larger. The difference is what happens at the end of the path. In a search an empty cell meant "not here"; in an insertion it means "right here". The value is written to items[i].

The new value takes no node's place and no cell is shifted. There can be no node below the cell where the path ends, because no node has an empty parent. That is why an inserted value is always a leaf.

Insertion is not done, and the function returns false, in two cases. If the value equals a node on the path, it is already in the tree; these lessons never keep the same value twice. If the end of the path falls outside the array (i >= CAPACITY), the value has a place but the array does not. The second case can happen even when the array still has empty cells.

The order of insertion decides the shape of the tree. The order 50, 30, 70 builds a balanced tree; the order 10, 20, 30, 40 builds a chain to the right, and four values use up 15 cells. The lesson The trouble with a BST in an array shows this in detail.

2Step by step

The drawing shows the example tree in the array and drawn below it. First 65 is inserted. Then 90 is inserted, and finally 85 is tried and its place turns out to be outside the array.

50030170220340460580678910111213145003017022034046058066512901465129014i
  1. insert(65) starts. i = 0: 50.
  2. 65 is larger than 50: i = 2, 70.
  3. 65 is smaller than 70: i = 5, 60.
  4. 65 is larger than 60: i = 2·5 + 2 = 12. Cell 12 is empty, so the loop ends.
  5. i is less than 15, so the place is inside the array. 65 is written to items[12]: it is now the right child of 60.
  6. The function returns true. No element moved; 65 is a new leaf.
  7. insert(90) goes through 50, 70 and 80 the same way, i = 2·6 + 2 = 14, and 90 is written to the last cell.
  8. insert(85): after 50, 70 and 80, 85 < 90, so i = 2·14 + 1 = 29. The array has 15 cells, so the place is outside it. Even with six empty cells in the array, the function returns false.

#define CAPACITY 15#define EMPTY -1 struct BST {    int items[CAPACITY];}; void create(struct BST* t) {    for (int i = 0; i < CAPACITY; i++) {        t->items[i] = EMPTY;    }} bool insert(struct BST* t, int value) {    int i = 0;    while (i < CAPACITY && t->items[i] != EMPTY) {        if (value == t->items[i]) {            return false;  // already there        }        if (value < t->items[i]) {            i = 2 * i + 1;  // go left        } else {            i = 2 * i + 2;  // go right        }    }    if (i >= CAPACITY) {        return false;  // the place is outside the array    }    t->items[i] = value;  // a new leaf    return true;}
class ArrayBST {    static final int EMPTY = -1;    int[] items;     ArrayBST(int capacity) {        items = new int[capacity];        java.util.Arrays.fill(items, EMPTY);    }     boolean insert(int value) {        int i = 0;        while (i < items.length && items[i] != EMPTY) {            if (value == items[i]) {                return false;  // already there            }            if (value < items[i]) {                i = 2 * i + 1;  // go left            } else {                i = 2 * i + 2;  // go right            }        }        if (i >= items.length) {            return false;  // the place is outside the array        }        items[i] = value;  // a new leaf        return true;    }}
class ArrayBST:    EMPTY = -1     def __init__(self, capacity):        self.items = [ArrayBST.EMPTY] * capacity     def insert(self, value):        i = 0        while i < len(self.items) and self.items[i] != ArrayBST.EMPTY:            if value == self.items[i]:                return False  # already there            if value < self.items[i]:                i = 2 * i + 1  # go left            else:                i = 2 * i + 2  # go right        if i >= len(self.items):            return False  # the place is outside the array        self.items[i] = value  # a new leaf        return True

The snippets focus on the operation in this lesson. The C examples need stdlib.h.

3Complexity

Time
O(h)

One comparison per level until the place is found; at most h + 1 steps, where h is the tree's . The write is O(1).

Memory
O(1)

Only i is used; the room is already set aside in the array.

In a balanced tree insertion takes , in a chain-shaped tree . Insertion with linked nodes takes the same number of steps but never runs out of places.

4Common mistake

A common mistake is writing without checking i after the loop:

t->items[i] = value;  // wrong: i may be 29

In the 85 example the loop ends with i = 29, and this line writes outside the array. In C it corrupts some other variable's memory; in Java it throws ArrayIndexOutOfBoundsException. Check i >= CAPACITY first. Skipping the equality check is also a mistake: the same value is added a second time to the right subtree and the tree ends up with two 50s.

5Try it

If 35 is inserted into the example tree (50, 30, 70, 20, 40, 60, 80), which index is it written to?

Show the answer

The answer is A. 35 < 50: i = 1 (30). 35 > 30: i = 4 (40). 35 < 40: i = 2·4 + 1 = 9. The cell is empty, so 35 is written to 9 as the left child of 40.

What happens if 40, 30, 20, 10, 5 are inserted in this order into an empty array BST with capacity 15?

Show the answer

The answer is B. Each value is smaller than the one before, so the path always goes left: 0, 1, 3, 7. For 5, i = 2·7 + 1 = 15, which is outside the array, so nothing is inserted.

Lessons you mark show up in the curriculum. If you are signed in, they are saved to your account too.