二叉树遍历~
学习ing~程序代码:
#include<stdio.h> #include<stdlib.h> typedef struct BitNode { char data; struct BitNode* lchild; struct BitNode* rchild; }BitNode,*Bitree; void creatbitree(BitNode** t,BitNode* point,int* n); //创建二叉树 void visit(BitNode* e); //打印二叉树 void preordertraverse(BitNode* t); //遍历二叉树 void countleaf(BitNode* t,int* c); //计算叶子数目 void destroybitree(BitNode* t); //释放二叉树 int treehigh(BitNode* t); //计算二叉树深度 int main() { BitNode* t=NULL; int count=0; int n=0; puts("Please initialize the TREE!"); creatbitree(&t,t,&n); puts("\nThis is TREE Struct:"); preordertraverse(t); countleaf(t,&count); printf("This TREE has %d leaves.\n",count); printf("High of the TREE is:%d.\n",treehigh(t)); destroybitree(t); return 0; } void creatbitree(BitNode** t,BitNode* point,int* n) //创建二叉树 { char x=0; BitNode* q=NULL; *n=*n+1; //计算节点个数 printf("\nNow the Bitree Point is:%o\nInput %d Data:",point,*n); x=getchar(); if (x!='\n') //吸收换行符 getchar(); if (x=='^') return ; q=(BitNode*)malloc(sizeof (BitNode)); q->data=x; q->lchild=NULL; q->rchild=NULL; *t=q; printf("This Address is:%o,Data is:%c\n",q,q->data); creatbitree(&q->lchild,q,n); creatbitree(&q->rchild,q,n); return ; } void visit(BitNode* e) { printf("Adress: %o,Data:%c,Left Pointer: %o,Right Pointer: %o\n",e,e->data,e->lchild,e->rchild); } void preordertraverse(BitNode* t) //遍历二叉树 { if (t) { visit(t); preordertraverse(t->lchild); preordertraverse(t->rchild); } return ; } void countleaf(BitNode* t,int* c) //计算叶子数目 { if (t==NULL) return ; if (t->lchild==NULL&&t->rchild==NULL) *c=*c+1; countleaf(t->lchild,c); countleaf(t->rchild,c); return ; } int treehigh(BitNode* t) { int lh=0; //左孩子深度 int rh=0; //右孩子深度 int h=0; //二叉树最大深度 if (t==NULL) return 0; lh=treehigh(t->lchild); rh=treehigh(t->rchild); h=(lh>rh?lh:rh)+1; return h; } void destroybitree(BitNode* t) { if (t) { destroybitree(t->lchild); destroybitree(t->rchild); } free(t); t=NULL; }