typedef char elemtype; struct node { elemtype data; struct node *lchild; struct node *rchild; }; typedef struct node btnode; typedef struct node *btree; void initbt(btree &t) {//初始化函数,构造一棵空树 t=NULL; } void createbt(btree &t) {//先序遍历序列创建二叉树 elemtype ch; cin>>ch; if(ch=='#') t=NULL;//#表示空树,递归终止 else { t=new btnode; if(t==NULL)//结点创建失败,退出 exit(-2); t->data=ch; createbt(t->lchild);//构造左子树 createbt(t->rchild);//构造右子树 } } int emptybt(btree t) {//判断树是否为空树 if(t==NULL) return 1; else return 0; } int depthbt(btree t) {//求二叉树b的深度 if(t==NULL) return 0; else { int depthl=depthbt(t->lchild); int depthr=depthbt(t->rchild); return 1+(depthl>depthr?depthl:depthr); } } int findnode(btree t,elemtype x) {//依照先序遍历,查找data域为x的结点是否存在 int i; if(t==NULL) return 0; else if(t->data==x) return 1; else { i=findnode(t->lchild,x); if(i!=0) return 1; else return findnode(t->rchild ,x); } } btree findnode1(btree t,elemtype x) {//依照先序遍历,查找data域为x的结点,返回结点指针 btree p; if(t==NULL) return NULL; else if(t->data==x) return t; else { p=findnode1(t->lchild,x); if(p!=NULL) return p; else return findnode1(t->rchild,x); } } void preorder(btree t) {//先序遍历的递归算法 if(t!=NULL) { cout<<t->data<<' '; preorder(t->lchild); preorder(t->rchild); } } void inorder(btree t) {//中序遍历的递归算法 if(t!=NULL) { inorder(t->lchild); cout<<t->data<<' '; inorder(t->rchild); } } void postorder(btree t) {//后序遍历的递归算法 if(t!=NULL) { postorder(t->lchild); postorder(t->rchild); cout<<t->data<<' '; } } void clearbt(btree &t) {//依照后序遍历的递归算法 if(t!=NULL) { clearbt(t->lchild); clearbt(t->rchild); delete t; t=NULL; } } void levelorder(btree t) {//借助循环队列的原理,实现层次遍历 btree queue[max];//定义循环队列 int front,rear; front=rear=0; if(t!=NULL) cout<<t->data<<' '; queue[rear]=t; rear++; while(rear!=front) { t=queue[front]; front=(front+1)%max; if(t->lchild!=NULL) { cout<<t->lchild->data<<' '; queue[rear]=t->lchild; rear=(rear+1)%max; } if(t->rchild!=NULL) { cout<<t->rchild->data<<' '; queue[rear]=t->rchild; rear=(rear+1)%max; } } } int nodecount(btree t) {//求二叉树t的结点个数 int num1,num2; if(t==NULL) return 0; else { num1=nodecount(t->lchild); num2=nodecount(t->rchild); return (num1+num2+1); } } void leafcount(btree t,int &count) {//求二叉树b的叶子结点个数 if(t!=NULL) { if(t->lchild==NULL&&t->rchild==NULL) count++; leafcount(t->lchild,count); leafcount(t->rchild,count); } } void displaybt(btree t) {//用广义表法输出二叉树 if(t!=NULL) { cout<<t->data; if(t->lchild!=NULL||t->rchild!=NULL) { cout<<'('; displaybt(t->lchild); if(t->rchild!=NULL) cout<<','; displaybt(t->rchild); cout<<')'; } } } void createbt1(btree &t,char *str) {//由广义表str串创建二叉链 btnode *st[max]; btnode *p=NULL; int top=-1,k,j=0; char ch; t=NULL; ch=str[j]; while(ch!='\0') { switch(ch) { case '(':top++;st[top]=p;k=1;break; case ')':top--;break; case ',':k=2;break; default:p=new btnode; p->data=ch;p->lchild=p->rchild=NULL; if(t==NULL) t=p; else { switch(k) { case 1:st[top]->lchild=p;break; case 2:st[top]->rchild=p;break; } } } j++; ch=str[j]; } }
注:来源为数据结构实验,非原创