Representing a tree with an array
You've seen two approaches to implementing a sequence data structure: either using an array, or using linked nodes. We extended our idea of linked nodes to implement a tree data structure. It turns out we can also use an array to represent a tree.
Here's how we implement a binary tree:
- The root of the tree will be in position 1 of the array (nothing is at position 0). We can define the position of every other node in the tree recursively:
- The left child of a node at position
n
is at position2n
. - The right child of a node at position
n
is at position2n + 1
. - The parent of a node at position
n
is at positionn/2
.
Self-test: ArrayBST representation
For each of the following self-tests, we will give you an instance of an ArrayBST. Match it to one of the four possible binary search trees below.
Tree 1 | Tree 2 | Tree 3 | Tree 4 |
Self-test 1
Which of tree options above could be represented by the
ArrayBST
shown here?Tree 1 |
Correct! The
ArrayBST suggests there is a root with one left child and no right child, and the left child has a left child.
|
|
Tree 2 |
Incorrect. The
ArrayBST shows the root has no right child.
|
|
Tree 3 |
Incorrect. The
ArrayBST shows the root has no right child.
|
|
Tree 4 |
Incorrect. The
ArrayBST shows the root has no right child.
|
Self-test 2
Which of tree options above could be represented by the
ArrayBST
shown here?Tree 1 |
Incorrect. The
ArrayBST shows that the root has a right child.
|
|
Tree 2 |
Correct! The
ArrayBST shows that the root has both a left and right child.
|
|
Tree 3 |
Incorrect. The
ArrayBST shows that the root has a left child.
|
|
Tree 4 |
Incorrect. The
ArrayBST shows that the root has a left child.
|
Self-test 3
Which of tree options above could be represented by the
ArrayBST
shown here?Tree 1 |
Incorrect. The
ArrayBST shows the root has no left child.
|
|
Tree 2 |
Incorrect. The
ArrayBST shows the root has no left child.
|
|
Tree 3 |
Correct! The
ArrayBST shows the root has a right child which has a left child.
|
|
Tree 4 |
Incorrect. Because there is nothing in position 7, the right child of the root can't have a right child.
|