《二叉樹(shù)的建立和遍歷C語(yǔ)言實(shí)現(xiàn)》由會(huì)員分享,可在線閱讀,更多相關(guān)《二叉樹(shù)的建立和遍歷C語(yǔ)言實(shí)現(xiàn)(4頁(yè)珍藏版)》請(qǐng)?jiān)谘b配圖網(wǎng)上搜索。
1、
#include
#include
typedef struct node{
int data;
struct node *ltree;
struct node *rtree;
}TNode;
//ADT of the Binary tree
TNode * create(TNode *);
int depth(TNode *);
int findmax(int,int);
void postorder(TNode *);
void inorder(TNode *);
void preorder(TNode *);
i
2、nt main()
{
TNode *tree;
printf("BinaryTree (By Recursion)\n\n");
tree=create(tree);
printf("\npreorder:\n");
preorder(tree);
printf("\ninorder:\n");
inorder(tree);
printf("\npostorder:\n");
postorder(tree);
printf("\nThe depth o the binary tree is: %d.\n",depth(tree))
3、;
return 0;
}//main
TNode * create(TNode * p)
{//創(chuàng)建一棵二叉樹(shù),返回根節(jié)點(diǎn)地址
int num;
scanf("%d",&num);
if(num==0){
return NULL;
}//if
p=(TNode *)malloc(sizeof(TNode));
p->data=num;//把數(shù)據(jù)賦值給數(shù)據(jù)域
p->ltree=create(p->ltree);//遞歸算法,創(chuàng)建左子樹(shù)
p->rtree=create(p->rtree);
return p;
}//create
vo
4、id preorder(TNode * p)
{
TNode* tree=p;
if(tree){
printf("%5d",p->data);
preorder(p->ltree);
preorder(p->rtree);
}
}//preorder
void inorder(TNode * p)
{
TNode* tree=p;
if(tree){
inorder(p->ltree);
printf("%5d",p->data);
inorder(p->rtree);
}
}//inorder
void postord
5、er(TNode * p)
{
TNode* tree=p;
if(tree){
postorder(p->ltree);
postorder(p->rtree);
printf("%5d",p->data);
}
}//postorder
int findmax(int x,int y)
{
return (x>y?x:y);
}//findmax
int depth(TNode * p)
{
TNode * tree=p;
int dep=0;
int depl,depr;
if(!p){
return 0;
}
depl=depth(p->ltree);
depr=depth(p->rtree);
dep=1+findmax(depl,depr);
return dep;
}//depth