#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct node
{
struct node *left;
struct node *right;
int value;
} Node;
static Node *p_node[100];
// for BSF way breadthorder
void enqueue( Node * p_data )
{
static i=0;
if( i >= 100 ) return ;
p_node[i] = p_data;
i++;
}
Node* dequeue( void )
{
static i=0;
if( i< 100 )
{ return p_node[i++]; }
else
{ return NULL; }
}
Node * insert(Node *r, int data)
{
if( NULL == r)
{
r = (Node *)malloc(sizeof(Node) );
if( NULL==r )
{ return NULL; }
r->value = data;
r->left = NULL;
r->right = NULL;
}
else if( data < r->value )
{ r->left = insert(r->left, data); }
else
{ r->right = insert(r->right, data); }
return r;
}
int get_tree_depth( Node * p_root )
{
int left_depth = 0;
int right_depth = 0;
if( NULL==p_root ) return 0;
left_depth = get_tree_depth( p_root->left );
right_depth = get_tree_depth( p_root->right );
if( left_depth > right_depth )
{ return (left_depth + 1); }
else
{ return (right_depth + 1); }
}
int get_node_count( Node * p_root )
{
if( NULL!=p_root )
{
return get_node_count( p_root->left) + get_node_count( p_root->right ) +1;
}
else
{ return 0; }
}
// this way needs a queue data structure
void breadthorder( Node *ptr_root )
{
if(NULL==ptr_root) return;
Node * p_tmp = ptr_root;
printf("%d ", ptr_root->value);
do
{
if( NULL!=p_tmp->left )
enqueue(p_tmp->left);
if( NULL!=p_tmp->right )
enqueue(p_tmp->right );
p_tmp = dequeue();
if( NULL!= p_tmp )
{ printf("%d ", p_tmp->value); }
else
{ break; }
} while( 1 ) ;
}
void preorder(Node *ptr_root)
{
if( NULL==ptr_root ) return ;
printf("%d ", ptr_root->value);
preorder( ptr_root->left );
preorder( ptr_root->right );
}
void inorder(Node *ptr_root)
{
if( NULL==ptr_root ) return ;
inorder( ptr_root->left );
printf("%d ", ptr_root->value);
inorder( ptr_root->right );
}
void postorder(Node *ptr_root)
{
if( NULL==ptr_root ) return ;
postorder( ptr_root->left );
postorder( ptr_root->right );
printf("%d ", ptr_root->value);
}
int main(void)
{
int n=0,v=0,i=0;
Node * root = NULL;
printf(" sizeof(int)=%ld\n", sizeof(int) );
printf("sizeof(float)=%ld\n", sizeof(float) );
printf("sizeof( Node * )=%ld\n", sizeof( Node *) );
printf("please input the data for the binary tree, n numbers please\n");
scanf("%d",&n);
for( i=0; i<n; i++ )
{
printf("data[%d]=\n",i);
scanf("%d", &v);
root = insert(root, v);
}
printf(" tree preoder result:\n");
preorder( root );
printf(" get_node_count=%d\n", get_node_count(root) );
printf(" get_tree_depth=%d\n", get_tree_depth(root) );
printf(" tree inoder result:\n");
inorder( root );
printf(" get_node_count=%d\n", get_node_count(root) );
printf(" tree postoder result:\n");
postorder( root );
printf(" get_node_count=%d\n", get_node_count(root) );
printf(" tree breadth search fist result:\n");
breadthorder( root );
printf(" get_node_count=%d\n", get_node_count(root) );
return 0;
}