注:本程序主要是关于二叉树的一些基本操作,包括前序遍历,中序遍历,后序遍历以及求出总结点以及叶子结点的数目(本程序在输入时是默认以先序序列输入各个结点的数值
如果是其它方式,则三个遍历程序会有略微变化)以及哈夫曼编码的输出
以下程序除汉字外均为在英文环境中编写,可直接复制到 VC 编程软件中运行
#include #include #include #include //getch()所需 int num; typedef struct node //定义二叉树的结构体 { char data; struct node *lchild,*rchild; }BinTNode,*BinTree; BinTree T; typedef struct //定义哈夫曼的结构体 { int weight; int parent,lchild,rchild; }HTNode,*HuffmanTree; HuffmanTree p; typedef char * *HuffmanCode; void CreateBinTree(BinTree &T) //建树 { char ch; ch=getch(); if (ch==' ') { printf("_"); T=NULL; } else { printf("%c",ch); T=(BinTNode *)malloc(sizeof(BinTNode)); T->data=ch; CreateBinTree(T->lchild ); CreateBinTree(T->rchild ); } } void Preorder(BinTree &T) //先序遍历 { if (T) { printf("%c",T->data); Preorder(T->lchild); Preorder(T->rchild); } } v