Problem :
There are several ways to traverse a tree, that is, to go through each of the
nodes in a tree. You can either start with the root node, then traverse the
two subtrees, or traverse the subtrees, then handle the root node, or traverse
the left subtree, then go through the root node, then traverse the right subtree.
The methods are called pre-order traversal, post-order traversal and infix
traversal respectively. Write a function that prints out the data elements in
a tree by traversing the tree with an infix traversal.
void print_infix (tree_t *t)
{
/* Base case */
if (t == NULL) return;
print_infix (t->left);
/* Print out the data element at the current node */
printf(" %d ", t->data);
print_infix (t->right);
}
Problem :
Write a recursive function in the canonical tree-recursion form that will
print out a valid English word when given the following tree as input.
(Hint: Think of the different traversals).
Problem 2
The solution here is to see that if you do a pre-fix traversal, except
traverse the right subtree before the left, you can spell the word
"programming".
void print_word (tree_t *t)
{
/* Base case */
if (t == NULL) return;
/* Print out the data element at the current node */
printf(" %d ", t->data);
print_word (t->right);
print_word (t->left);
}
Problem :
Describe an algorithm for writing a level-order traversal, where all of the
nodes at depth 0 are printed, then depth 1, then depth 2, etc
One way to do this might be to first determine the maximum depth. Then
iterate through each depth, and call a function that will print out all
of the nodes at a given depth. Such a function could work by taking two
arguments, a tree and a number. If the number passed it zero, then it will
print the data value in the root of the tree, otherwise it will recursively
call itself with the two subtrees and the number decremented by one. So if
this function is called with the root of the tree and the desired depth, the
recursive calls will have a number of zero when the tree passed is a tree at
the proper depth.