1>请编程实现二又树的操作
1.1二又树的创建
1.2二又树的先序遍历
1.3二又树的中序遍历
1.4二又树的后序遍历
1.5二又树各个节点度的个数
1.6二叉树的深度
代码:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef char datatype;
typedef struct Btree{
datatype data;
struct Btree *lchild,*rchild;
}*btree;
btree node_create(){
btree p=(btree)malloc(sizeof(struct Btree));
if(!p)
return NULL;
p->data='\0';
p->lchild=NULL;
p->rchild=NULL;
return p;
}
btree tree_create(){
datatype e;
scanf("%c",&e);
getchar();
if(e=='#')
return NULL;
btree p=node_create();
p->data=e;
p->lchild=tree_create();
p->rchild=tree_create();
return p;
}
void first(btree root){
if(!root)
return;
printf("%c\t",root->data);
first(root->lchild);
first(root->rchild);
}
void mid(btree root){
if(!root)
return;
mid(root->lchild);
printf("%c\t",root->data);
mid(root->rchild);
}
void last(btree root){
if(!root)
return;
last(root->lchild);
last(root->rchild);
printf("%c\t",root->data);
}
int count(btree root,int *n0,int *n1,int *n2){
if(!root)
return 0;
if(!root->lchild&&!root->rchild)
++*n0;
else if(root->lchild&&root->rchild)
++*n2;
else
++*n1;
count(root->lchild,n0,n1,n2);
count(root->rchild,n0,n1,n2);
}
int depth(btree root){
if(!root)
return 0;
int left=1+depth(root->lchild);
int right=1+depth(root->rchild);
return left>right?left:right;
}
int main(int argc,const char*argv[]){
btree root=NULL;
root=tree_create();
first(root);
puts("");
mid(root);
puts("");
last(root);
puts("");
int n0=0,n1=0,n2=0;
count(root,&n0,&n1,&n2);
printf("n0=%d n1=%d n2=%d sum=%d\n",n0,n1,n2,n0+n1+n2);
int len=depth(root);
printf("二叉树深度为%d\n",len);
return 0;
}
结果: