# 6: Binary Trees

- Page ID
- 8460

This chapter introduces one of the most fundamental structures in computer science: binary trees. The use of the word tree here comes from the fact that, when we draw them, the resultant drawing often resembles the trees found in a forest. There are many ways of ways of defining binary trees. Mathematically, a binary tree is a connected, undirected, finite graph with no cycles, and no vertex of degree greater than three.

For most computer science applications, binary trees are rooted: A special node, \(\mathtt{r}\), of degree at most two is called the root of the tree. For every node, \(\mathtt{u}\neq \mathtt{r}\), the second node on the path from \(\mathtt{u}\) to \(\mathtt{r}\) is called the parent of \(\mathtt{u}\). Each of the other nodes adjacent to \(\mathtt{u}\) is called a child of \(\mathtt{u}\). Most of the binary trees we are interested in are ordered, so we distinguish between the left child and right child of \(\mathtt{u}\).

In illustrations, binary trees are usually drawn from the root downward, with the root at the top of the drawing and the left and right children respectively given by left and right positions in the drawing (Figure \(\PageIndex{1}\)). For example, Figure \(\PageIndex{2}\).a shows a binary tree with nine nodes.

Because binary trees are so important, a certain terminology has developed for them: The depth of a node, \(\mathtt{u}\), in a binary tree is the length of the path from \(\mathtt{u}\) to the root of the tree. If a node, \(\mathtt{w}\), is on the path from \(\mathtt{u}\) to \(\mathtt{r}\), then \(\mathtt{w}\) is called an ancestor of \(\mathtt{u}\) and \(\mathtt{u}\) a descendant of \(\mathtt{w}\). The subtree of a node, \(\mathtt{u}\), is the binary tree that is rooted at \(\mathtt{u}\) and contains all of \(\mathtt{u}\)'s descendants. The height of a node, \(\mathtt{u}\), is the length of the longest path from \(\mathtt{u}\) to one of its descendants. The height of a tree is the height of its root. A node, \(\mathtt{u}\), is a leaf if it has no children.

We sometimes think of the tree as being augmented with external nodes. Any node that does not have a left child has an external node as its left child, and, correspondingly, any node that does not have a right child has an external node as its right child (see Figure \(\PageIndex{1}\).b). It is easy to verify, by induction, that a binary tree with \(\mathtt{n}\ge 1\) real nodes has \(\mathtt{n}+1\) external nodes.