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

Search, node count and height

The three questions asked of a tree most often are: is this value in the tree, how many nodes does it have, and how tall is it? For a tree in an array the first answer is a plain loop. The other two follow the same recursion pattern as the traversals, and they are used unchanged with linked nodes.

What you will learn
  • Why searching an unordered tree has to look at every node
  • How to compute the node count and the height with the pattern "me plus my subtrees"
  • Why the height of a complete tree is the whole part of log2(n)
6 minTime O(n)Memory O(h)C · Java · Python

1Idea

Search

In this tree the values are not ordered; there is no way to know whether a value lies left or right. So the search scans the used part of the array from start to end and returns the index when it finds the value. If it does not, it returns -1. The loop stops at count; the cells after it are not part of the tree.

Node count

The number of nodes in a subtree is 1 for its root, plus the nodes in the left subtree, plus the nodes in the right subtree. At an empty place (i >= count) the count is 0. In an array this number is already in count, but the same function also gives the size of a subtree: countNodes(t, 1) counts the 3 nodes in the subtree of 20.

Height

is the number of edges on the path from a node down to its farthest leaf. A node's height is one more than the height of its taller subtree. An empty tree is given height -1, so a comes out as 1 + max(-1, -1) = 0.

Since the tree in an array is , the height also has a formula: a tree with n nodes has height equal to the whole part of log2(n). With 6 nodes log2(6) is about 2.58, so the height is 2. With 8 nodes a new level opens and the height becomes 3.

Some books measure height in levels instead of edges: a one-node tree is 1 and an empty tree 0. With that definition the base case returns 0 and every result goes up by one. In an exam, check which definition is meant.

2Step by step

The drawing first searches for 50, then works out each node's height from the bottom up, and finally shows the node counts. The computed value is written under each tree node.

items1001002012013023024034035045046056056i
  1. Start. count is 6. First search(50) is called.
  2. i = 0: items[0] is 10, not 50. Keep going.
  3. i = 1: 20, not 50.
  4. i = 2: 30, not 50. The tree is not ordered, so no cell can be skipped.
  5. i = 3: 40, not 50.
  6. i = 4: items[4] is 50. Found; the function returns 4. Five comparisons were made.
  7. Now height(t, 0). The recursion goes down to the leaves. The child calls of 40, 50 and 60 hit empty places and return -1, so each leaf has height 1 + max(-1, -1) = 0.
  8. The height of 20 is 1 + max(0, 0) = 1. 30 has no right child: 1 + max(0, -1) = 1.
  9. The root: 1 + max(1, 1) = 2. The tree's height is 2. The whole part of log2(6) is 2 as well.
  10. countNodes follows the same pattern: the leaves give 1, the subtree of 20 gives 1 + 1 + 1 = 3, that of 30 1 + 1 + 0 = 2, the root 1 + 3 + 2 = 6.

#define CAPACITY 15 struct Tree {    int items[CAPACITY];    int count;}; int search(struct Tree* t, int value) {    for (int i = 0; i < t->count; i++) {        if (t->items[i] == value) {            return i;  // found: its index        }    }    return -1;  // not in the tree} int countNodes(struct Tree* t, int i) {    if (i >= t->count) {        return 0;    }    return 1 + countNodes(t, 2 * i + 1) + countNodes(t, 2 * i + 2);} int height(struct Tree* t, int i) {    if (i >= t->count) {        return -1;  // height of an empty tree    }    int leftH = height(t, 2 * i + 1);    int rightH = height(t, 2 * i + 2);    return 1 + (leftH > rightH ? leftH : rightH);}
class ArrayTree {    int[] items;    int count = 0;     ArrayTree(int capacity) {        items = new int[capacity];    }     int search(int value) {        for (int i = 0; i < count; i++) {            if (items[i] == value) {                return i;  // found: its index            }        }        return -1;  // not in the tree    }     int countNodes(int i) {        if (i >= count) {            return 0;        }        return 1 + countNodes(2 * i + 1) + countNodes(2 * i + 2);    }     int height(int i) {        if (i >= count) {            return -1;  // height of an empty tree        }        int leftH = height(2 * i + 1);        int rightH = height(2 * i + 2);        return 1 + Math.max(leftH, rightH);    }}
class ArrayTree:    def __init__(self, capacity):        self.items = [None] * capacity        self.count = 0     def search(self, value):        for i in range(self.count):            if self.items[i] == value:                return i  # found: its index        return -1  # not in the tree     def count_nodes(self, i=0):        if i >= self.count:            return 0        return 1 + self.count_nodes(2 * i + 1) + self.count_nodes(2 * i + 2)     def height(self, i=0):        if i >= self.count:            return -1  # height of an empty tree        left_h = self.height(2 * i + 1)        right_h = self.height(2 * i + 2)        return 1 + max(left_h, right_h)

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

3Complexity

Time
O(n)

The search looks at every node in the worst case. The node count and the height visit each node once.

Memory
O(h)

The search uses O(1) space. The call stack of the two recursive functions gets as deep as the tree's height; for a complete tree that is log n.

If the values were placed by a rule, the search would not take this long. In a binary search tree one subtree is dropped at every step.

4Common mistake

A common mistake is returning 0 for an empty tree in the height function and mixing up the definitions:

if (i >= t->count) {    return 0;  // wrong with the edge definition: a leaf comes out as 1}

With height measured in edges a leaf must be 0, and for that an empty tree returns -1. Returning 0 switches to the level-count definition. Mixing the two shifts every result by one. Another mistake is adding instead of taking max, or looking only at the left subtree; the longest path can be on the right too.

5Try it

What is the height of a binary tree with 12 nodes stored in an array in level order? (A one-node tree has height 0.)

Show the answer

The answer is A. The tree is complete. A complete tree with 8 to 15 nodes has height 3: log2(12) is about 3.58, whose whole part is 3.

How many comparisons does searching this tree for a value take in the worst case?

Show the answer

The answer is B. The values are not placed in order, so no cell can be skipped. If the value is missing or last, all n nodes are checked.

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