#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
struct tree_node
{
int data;
struct tree_node *left_ptr;
struct tree_node *right_ptr;
};
void insert_node(struct tree_node **, int);
void pre_order(struct tree_node *);
void in_order(struct tree_node*);
void post_order(struct tree_node*);
int main()
{
int i, item;
struct tree_node* root_ptr = NULL;
srand(time(NULL));
for(i=0; i<10; i++)
{
item = rand()%15;
printf("%3d", item);
insert_node(&root_ptr, item);
}
puts("pre_order");
pre_order(root_ptr);
puts("in_order");
in_order(root_ptr);
puts("post_order");
post_order(root_ptr);
return EXIT_SUCCESS;
}
void insert_node(struct tree_node **tree_ptr, int value)
{
if (*tree_ptr == NULL)
{
*tree_ptr = malloc(sizeof(struct tree_node));
if (*tree_ptr != NULL)//malloc successfully
{
(*tree_ptr)->data = value;
(*tree_ptr)->left_ptr = NULL;
(*tree_ptr)->right_ptr = NULL;
}
else
{
printf("%d not inserted. No memory available\n", value);
}
}
else//the tree is not null
{
if (value < (*tree_ptr)->data)
{
insert_node(&((*tree_ptr)->left_ptr), value);
}
else if (value > (*tree_ptr)->data)
{
insert_node(&((*tree_ptr)->right_ptr), value);
}
else//the equal value is not inserted
{
puts("dup");
}
}
}
void pre_order(struct tree_node *ptr)
{
if (ptr != NULL)
{
printf("%3d", ptr->data);
pre_order(ptr->left_ptr);
pre_order(ptr->right_ptr);
}
}
void in_order(struct tree_node *ptr)
{
if (ptr != NULL)
{
in_order(ptr->left_ptr);
printf("%3d", ptr->data);
in_order(ptr->right_ptr);
}
}
void post_order(struct tree_node *ptr)
{
if (ptr != NULL)
{
post_order(ptr->left_ptr);
post_order(ptr->right_ptr);
printf("%3d", ptr->data);
}
}
二叉排序树
最新推荐文章于 2024-04-21 11:01:55 发布