本博客将以代码的形式详细讲解二叉树的所有算法,包括创建二叉树,二叉树的三种遍历方式,二叉树的各种属性算法,如:求高度,求叶子节点数,求节点数,以及二叉树最常见的应用哈夫曼树,代码如下:
# include程序运行结果如下:# include # include # include # define N 1# define M 2*N-1typedef char * HC[N+1];typedef struct bt{ char x; struct bt *lchild; struct bt *rchild;}bt,*pbt;typedef struct { int parent; int weight, lchild, rchild;}HT[M+1];void creatbt(pbt *root){ char ch=getchar(); if(ch==' ') *root=NULL; else { *root=(pbt)malloc(sizeof(bt)); (*root)->x=ch; creatbt(&((*root)->lchild)); creatbt(&((*root)->rchild)); }}void preorder(pbt root){ if(root!=NULL) { printf("%c",root->x); preorder(root->lchild); preorder(root->rchild); }}void inorder(pbt root){ if(root!=NULL) { inorder(root->lchild); printf("%c",root->x); inorder(root->rchild); }}void postorder(pbt root){ if(root!=NULL) { postorder(root->lchild); postorder(root->rchild); printf("%c",root->x); }}int btdepth(pbt root,int h){ static int depth=0; if(root!=NULL) { if(h>depth) depth=h; btdepth(root->lchild,h+1); btdepth(root->rchild,h+1); } return depth;}int nodenum(pbt root){ static int n=0; if(root!=NULL) { n++; nodenum(root->lchild); nodenum(root->rchild); } return n;}int leafnum(pbt root){ static int n=0; if(root!=NULL) { leafnum(root->lchild); leafnum(root->rchild); if((root->lchild==NULL)&&(root->rchild==NULL)) n++; } return n;}void select(HT ht,int n,int *x,int *y){ int i,min1=100,min2=200; for(i=1;i<=n;i++) { if(ht[i].parent==0&&ht[i].weight
注意对于同一个二叉树,哈夫曼码的结果不唯一,上述输出只是一种情况。