Skip over navigation

Implementation of Trees

Problems 1

Implementation with Structs and Pointers

Implementation with Arrays

Problem : As discussed above, each node in our implementation contains an integer as the only data element. Rewrite the typedef so that it contains age (an int) as one field and a string name as the other.


typedef struct _tree {
	int		age;
	char 		*name;
	struct _tree	*left, *right;
} tree_t'

Problem : With the old definition, declaring a variable to be a tree_t allocated all of the space for the tree and its data, is that still true with the new definition? Explain.

This is no longer true for practical purposes. The reason is that it contains only a pointer to the start of the name string in memory. It does not, however, contain the space for the name itself. If you wished to do this, you would need to decide a limit on the number of characters beforehand and then replace the line

	char 		*name;
with

	char		name[MAX + 1];
Notice that we add one to the maximum number of characters to hold the null character that marks the end of a string. We could also allocate memory dynamically to store the name string.

Problem : Describe what you know about the values of the fields for a leaf node in this implementation.

Because it is a leaf node, we know that it has no children, by definition. In other words, it does not branch at all. The way that we indicate the lack of a branch is to make the pointer for that branch NULL. Because the leaf does not branch we therefore know that both its left and its right subtree pointers are NULL.

Follow Us