Binary Trees in C++
(Translated from the Java Verstion, see
http://math.hws.edu/javanotes/c11/s4.html)
W
E HAVE SEEN how objects can be linked into lists. When an object contains two pointers to
objects of the same type, structures can be created that are much more complicated than linked lists. In
this section, we'll look at one of the most basic and useful structures of this type:
binary trees
. Each of
the objects in a binary tree contains two pointers, typically called
left
and
right
. In addition to these
pointers, of course, the nodes can contain other types of data. For example, a binary tree of integers
could be made up of objects of the following type:
struct TreeNode {
int item;
// The data in this node.
TreeNode *left;
// Pointer to the left subtree.
TreeNode *right;
// Pointer to the right subtree.
}
The
left
and
right
pointers in a
TreeNode
can be
NULL
or
can point to other objects of type
TreeNode
. A node that
points to another node is said to be the
parent
of that node,
and the node it points to is called a
child
. In the picture at the
right, for example, node 3 is the parent of node 6, and nodes 4
and 5 are children of node 2. Not every linked structure made
up of tree nodes is a binary tree. A binary tree must have the
following properties: There is exactly one node in the tree
which has no parent. This node is called the
root
of the tree.
Every other node in the tree has exactly one parent. Finally,
there can be no loops in a binary tree. That is, it is not
possible to follow a chain of pointers starting at some node
and arriving back at the same node.
A node that has no children is called a
leaf
. A leaf node can
be recognized by the fact that both the left and right pointers
in the node are
NULL
. In the standard picture of a binary tree,
the root node is shown at the top and the leaf nodes at the
bottom -- which doesn't show much respect with the analogy
to real trees. But at least you can see the branching, tree-like structure that gives a binary tree its name.
Consider any node in a binary tree. Look at that node together with all its descendents (that is, its
children, the children of its children, and so on). This set of nodes forms a binary tree, which is called
a
subtree
of the original tree. For example, in the picture, nodes 2, 4, and 5 form a subtree. This
subtree is called the
left subtree
of the root. Similarly, nodes 3 and 6 make up the
right subtree
of the
root. We can consider any non-empty binary tree to be made up of a root node, a left subtree, and a
right subtree. Either or both of the subtrees can be empty. This is a
recursive
definition, matching the
recursive definition of the
TreeNode
class. So it should not be a surprise that recursive functions are
often used to process trees.
Consider the problem of counting the nodes in a binary tree. As an exercise, you might try to come up