CMUQ 15-121 More With Trees



1. Introduction

In this set of notes we’ll expand a on binary trees by giving some final terminology for them and discussing an alternative way to store them.

2. More Tree Vocabulary

Let’s look at three more vocabulary words related to binary trees.

2.1. Full Binary Tree

A full binary tree is a tree where each node has exactly 0 or 2 children. Here is an example:

Full binary tree

2.2. Complete Binary Tree

A complete binary tree is one where every level except the last one is completely filled, and the last level has all leaves as far left as possible. Here is an example:

Complete binary tree

Notice that the example from the previous section (under full binary tree) is not a complete binary tree because the level containing 7 and 12 is not full.

2.3. Perfect Binary Tree

A perfect binary tree is like a complete binary tree where the last level is also full. Another way to define it is to say that all internal nodes have two children and all leaf nodes are at the same depth. Here is an example:

Perfect binary tree

As an interesting side-note, all perfect trees are also full and complete.

3. Another Way to Store Trees

Consider the following binary tree:

Thus far, we’ve stored binary trees by creating TreeNodes who each have a left and right pointer and forming the tree that way. However, there is an alternative way to store a binary tree using an array. Here is an array representation of that same tree:

Notice the following properties:

This is a valid way to store trees, and is actually simpler than storing pointers to nodes and such. The main downside of this approach, however, is wasted space. If a tree isn’t perfect, then there are empty spaces in the array.