322 Intermediate C Programming
(a) (b) (c) (d)
(e) (f) (g)
(h) (i) (j)
FIGURE 20.7: Insert values 8, 4, 11, 1, 9, 7, 10, 5, 12, 15.
Fig. 20.4 shows the tree after inserting two nodes. Since −504 is smaller than 917, the
second node is inserted to the left of the first node. This is an essential property of binary
search trees. Also, note that the root’s value (the address of the root node) does not change
after inserting the first node. In this example, the value remains 60000.
Fig. 20.5 shows that another tree node is inserted. The value is 1226 and it is larger
than 917. Thus, it is inserted to the right side of the first node. Fig. 20.6 shows a tree with
five tree nodes. The second view in (b) quickly becomes complicated as more nodes are
inserted. The memory view is also getting quite long. Thus, a different representation is
more convenient, as shown in Fig. 20.6 (d). In this view, each tree node is represented as an
oval. Note that “tree”s are drawn upside down, i.e., the root is at the top. This is different
from the trees seen in forests.
The values −504 and 73 are smaller than the value at root, so both tree nodes are at
the left side of root. Because 73 is larger than −504, 73 is at the right side of −504. Binary
search tree has an important property: For any tree node whose value is val, all tree nodes
on the left side have values smaller than val. Furthermore, all tree nodes on the right side
have values larger than val. Fig. 20.7 shows a binary search as values are inserted. The first
inserted value is the tree’s root.
The following code listing gives an implementation Tree insert, as well as an auxiliary
function TreeNode construct. It is static because it should not be called by any function
outside this file. When inserting a new value into a binary search tree, a new leaf node is
created. That means that the new node never has any children. Tree insert is similar to
the insert function in Section 19.1, where a linked list is used as a queue, and the newly
created node is placed at the end.
// tre einsert .c1
#in clude " tree .h "2