algoritmauzmanı
Sign in
TREN
6.2Binary Tree with an Array
Lesson 6.2.2

Insert: into the next free place

Where does a new node go in a binary tree? In the tree of this subtopic the rule is simple: the tree fills level by level, left to right on each level. In an array that means the first empty cell, and its index is already known: count.

What you will learn
  • Why a new node is written to items[count]
  • Why this rule keeps the tree
  • How to find the new node's parent, and whether it is a left or right child, from its index
5 minTime O(1)Memory O(1)C · Java · Python

1Idea

If the tree has count nodes, the used cells run from 0 to count - 1 and the first empty cell is cell count. Insertion takes two lines: write the value to items[count], then add one to count. No element is shifted.

The new node's place in the tree is read from its index. Its parent is at (count-1)/2. An odd index means a left child and an even one a right child, because left children land at 2*i+1 and right children at 2*i+2. In the example 60 goes into cell 5: its parent is (5-1)/2 = 2, which is 30, and since 5 is odd it is the left child.

Because the tree always grows into the first empty cell, no gaps appear in the array. That means the tree is a : every level except the last is full, and the last one fills from the left. All the traversal and search code relies on this.

When the array is full (count == CAPACITY) there is no room: C returns false, Java and Python throw an error. With a capacity of 15 the tree stops once its fourth level is full.

This insertion ignores the values; a node is placed only by order. In a binary search tree the place is chosen by value instead, and gaps appear in the array.

2Step by step

The drawing shows a tree that already holds 10, 20, 30, 40, 50. First 60 is inserted, then 70. The tree is on top, the array below and count on the right.

items100100201201302302403403504504605605706706565count6count7count
  1. Start. count is 5: the used cells run from 0 to 4. The last level of the tree has two free places, both under 30.
  2. insert(60). First the full check: count is 5 and the capacity is 15. There is room.
  3. 60 is written to items[5], the first empty cell. Its parent is (5-1)/2 = 2: 30. Since 5 is odd, it is the left child of 30.
  4. count becomes 6. The tree still has no gaps: the used cells run from 0 to 5.
  5. insert(70). There is room; 70 is written to items[6]. Its parent is (6-1)/2 = 2, 30 again. Since 6 is even, it is the right child.
  6. count becomes 7. Three levels are full: 1 + 2 + 4 = 7 nodes. The next insertion starts the fourth level, as the left child of 40.

#define CAPACITY 15 struct Tree {    int items[CAPACITY];    int count;}; bool insert(struct Tree* t, int value) {    if (t->count == CAPACITY) {        return false;  // tree is full    }    t->items[t->count] = value;  // the next free place    t->count++;    return true;}
class ArrayTree {    int[] items;    int count = 0;     ArrayTree(int capacity) {        items = new int[capacity];    }     void insert(int value) {        if (count == items.length) {            throw new IllegalStateException("tree is full");        }        items[count] = value;  // the next free place        count++;    }}
class ArrayTree:    def __init__(self, capacity):        self.items = [None] * capacity        self.count = 0     def insert(self, value):        if self.count == len(self.items):            raise IndexError("tree is full")        self.items[self.count] = value  # the next free place        self.count += 1

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

3Complexity

Time
O(1)

One comparison, one write and one increment. The number of nodes in the tree does not matter.

Memory
O(1)

The room is already set aside in the array; insertion asks for no new memory.

With linked nodes, finding the same place means walking the tree level by level with a queue; that insertion takes O(n). In the array the index of the first free place is ready in count.

4Common mistake

A common mistake is increasing count before writing:

t->count++;t->items[t->count] = value;  // wrong: one cell stays empty

Now the value goes into cell count + 1 and an empty cell is left in between. The tree is no longer complete; a meaningless value sits at an index below count, and the traversals print it too. At the capacity limit the write goes past the end of the array. The right order is write first, then increase.

5Try it

The tree has 9 nodes (count = 9). Which index does the new node go into, and at which index is its parent?

Show the answer

The answer is A. The first empty cell is count = 9. The parent is (9-1)/2 = 4. Since 9 is odd, the new node is the left child of 4.

Which property of the tree does this way of inserting keep?

Show the answer

The answer is B. Nodes always go into the first empty cell, so the used cells run from 0 to count - 1 with no gaps; the tree stays complete. The values are ignored, so no order is kept, and some nodes may have only one child.

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