Search Menu


Problems 2

Problems 2

Problem : Use our array implementation to draw the tree that corresponds to the following array:

Figure %: Solution 1
The process for determining what the tree looks like is to assume a perfect tree corresponding to the number of cells in the array and then to fill in successive rows in the tree (nodes of the same depth). If a cell is EMPTY, it means that the parent node has a null pointer to it.

Problem : What is problematic about the following tree?

#define EMPTY	0

int array[] = {0, 1, EMPTY, 1, 4, 0, EMPTY};

As explained in the section, it is necessary that the value of ~EMPTY~ not be a valid value for the data in the tree. If it is, then it is unclear whether that value corresponds to an empty cell or a node with that data value. Here the number 0 is ambiguous.

Problem : If you know that a node corresponds to index i the array, what would be the index of its parent?

We know that if a parent is at index n, then its children are at indices 2 * n + 1 and 2 * n + 2. Working backwards, if i is odd, then subtract 1, otherwise subtract 2. Then divide by 2 and you have the index of the parent node.