How do I count the nodes? i have got so far :
Code:
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
typedef int data_t; /* For a tree of ints */
#include "treeops.c"
int
main ()
{
int value, size=0;
tree_t *tree;
node_t *result;
tree = make_empty_tree ();
/** your experimentatation code goes here **/
printf("Enter some value onto a tree for testing: ");
while (scanf("%d", &value)!=EOF)
{
tree = insert_in_order (tree, value);
}
size = tree_size(tree);
printf("The size of the tree is: ");
printf("%d", size);
/** Clean up the mess **/
free_tree (tree);
tree = NULL;
/** Exit gracefully **/
return (EXIT_SUCCESS);
}
int
tree_size(tree_t *tree) {
node_t *ptr;
ptr = tree->root;
return num_nodes(ptr);
}
int
num_nodes(node_t *root) {
if (root==NULL)
{
return 0;
}
else
{
return (1 + num_nodes(root->left) + num_nodes(root->right));
}
}
tree_t
*insert_in_order (tree_t *tree, data_t value)
{
/* make new node */
node_t *new;
new = malloc (sizeof (node_t));
assert (tree!=NULL && new!=NULL);
new->data = value;
new->left = NULL;
new->right = NULL;
/* insert node in tree */
tree->root = recursive_insert (tree->root, new);
return tree;
}
Is there a better way to write tree_size to not include num_nodes. I find tree_size hard to deal with because it is passed a tree_t pointer, not a node_t and so cant recurse