1、二叉树的操作
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
typedef char datatype;
typedef struct Node
{
//数据域
datatype data;
//左孩子指针
struct Node *lchild;
//右孩子指针
struct Node *rchild;
}*Btree;
Btree create_node()
{
Btree s=(Btree)malloc(sizeof(struct Node));
if(s==NULL)
return NULL;
s->data=0;
s->lchild=s->rchild=NULL;
return s;
}
Btree create_tree()
{
datatype element;
printf("please enter the element:");
scanf(" %c",&element);
if(element=='#')
return NULL;
//创建节点
Btree tree=create_node();
tree->data=element;
//循环递归左孩子
puts("left");
tree->lchild=create_tree();
//循环递归右孩子
puts("right");
tree->rchild=create_tree();
return tree;
}
void first_output(Btree tree)
{
if(tree==NULL)
return;
//遍历根节点
printf("%c",tree->data);
//遍历左孩子
first_output(tree->lchild);
//遍历右孩子
first_output(tree->rchild);
}
void mid_output(Btree tree)
{
if(tree==NULL)
return;
//遍历左孩子
mid_output(tree->lchild);
//遍历根节点
printf("%c",tree->data);
//遍历右孩子
mid_output(tree->rchild);
}
void last_output(Btree tree)
{
if(NULL==tree)
return;
//遍历左孩子
last_output(tree->lchild);
//遍历右孩子
last_output(tree->rchild);
//遍历根节点
printf("%c",tree->data);
}
void count_tree(Btree tree,int *n0,int *n1,int *n2)
{
if(tree==NULL)
return;
if(!tree->lchild && !tree->rchild)
++*n0;
else if(tree->lchild && tree->rchild)
++*n2;
else
++*n1;
//递归左孩子
count_tree(tree->lchild,n0,n1,n2);
//递归右孩子
count_tree(tree->rchild,n0,n1,n2);
}
int high_tree(Btree tree)
{
if(tree==NULL)
return 0;
//递归左子树
int left=1+high_tree(tree->lchild);
//递归右子树
int right=1+high_tree(tree->rchild);
return left>right?left:right;
}
int main(int argc, const char *argv[])
{
//创建二叉树
Btree tree=create_tree();
//先序遍历
first_output(tree);
puts("");
//中序遍历
mid_output(tree);
puts("");
//后序遍历
last_output(tree);
puts("");
//计算个节点的度
int n0=0,n1=0,n2=0;
count_tree(tree,&n0,&n1,&n2);
printf("n0=%d n1=%d n2=%d n=%d\n",n0,n1,n2,n0+n1+n2);
//计算树的深度
int high=high_tree(tree);
printf("the tree high is:%d\n",high);
return 0;
}