Natural Correspondence: Binary Tree Representation of Forest Forest Traversal

J.E.D.I Figure 1.62 Binary Tree Node With this structure, LEFT points to the leftmost son of the node while RIGHT points to the next younger brother.

5.4 Forests

When zero or more disjoint trees are taken together, they are known as a forest. The following forest is an example: Figure 1.63 Forest F If the trees comprising a forest are ordered trees and if their order in the forest is material, it is known as ordered forest.

5.4.1 Natural Correspondence: Binary Tree Representation of Forest

An ordered forest, say F, may be converted into a unique binary tree, say BF, and vice versa using a well-defined process known as natural correspondence. Formally: Let F = T 1 , T 2 , ..., T n be an ordered forest of ordered trees. The binary tree BF corresponding to F is obtained as follows: • If n = 0, then BF is empty. • If n 0, then the root of BF is the root of T 1 ; the left subtree of BF is B T 11 , T 12 , ... T 1m where T 11 , T 12 , ... T 1m are the subtrees of the root of Data Structures 75 J.E.D.I T 1 ; and the right subtree of BF is B T 2 , T 3 , ..., T n . Natural correspondence may be implemented using non-recursive approach: 1. Link together the sons in each family from left to right. Note: the roots of the tree in the forest are brothers, sons of an unknown father. 2. Remove links from a father to all his sons except the oldest or leftmost son. 3. Tilt the resulting figure by 45 degrees. The following example illustrates the transformation of a forest into its binary tree equivalent: Data Structures 76 J.E.D.I Figure 1.64 Example of Natural Correspondence In natural correspondence, the root is replaced by the root of the first tree, the left subtree is replaced by subtrees of the first tree and the right subtree is replaced by the remaining trees.

5.4.2 Forest Traversal

Just like binary trees, forests can also be traversed. However, since the concept of middle node is not defined, a forest can only be traversed in preorder and postorder. Data Structures 77 J.E.D.I If the forest is empty, traversal is considered done; otherwise: • Preorder Traversal 1. Visit the root of the first tree. 2. Traverse the subtrees of the first tree in preorder. 3. Traverse the remaining trees in preorder. • Postorder Traversal 1. Traverse the subtrees of the first tree in postorder. 2. Visit the root of the first tree. 3. Traverse the remaining trees in postorder. Figure 1.65 Forest F Forest preorder : A B C D E F G H I K J L M N Forest postorder : C D E F B A H K I L J G N M The binary tree equivalent of the forest will result to the following listing for preorder, inorder and postorder BF preorder : A B C D E F G H I K J L M N BF inorder : C D E F B A H K I L J G N M BF postorder : F E D C B K L J I H N M G A Notice that forest postorder yields the same result as BF inorder. It is not a coincidence.

5.4.3 Sequential Representation of Forests