算法设计:
1. 编写一个程序完成统计一个二叉树的中叶子结点的个数。
2. 设计一个算法,完成计算一个二叉树的高度。
3. 判定一个二叉树是否为完全二叉树
#include<stdio.h>
#include<stdlib.h>
#define MAXSIZE 50
typedef struct Node{
char data;
struct Node *lchild;
struct Node *rchild;
}BiTreeNode,*BiTree;
BiTree CreateTree();
void PreOrder(BiTree root);
void InOrder(BiTree root);
int leafnode(BiTree root);
int highth(BiTree root);
int completetree(BiTree root);
int main()
{
BiTree t=NULL;
printf("请输入二叉树(如无孩子请输入#):");
t=CreateTree();
printf("先序遍历:");
PreOrder(t);
printf("\n中序遍历:");
InOrder(t);
printf("\n叶子结点数=%d\n",leafnode(t));
printf("树的高度=%d\n\n",highth(t));
if(completetree(t)==1)
printf("此二叉树是完全二叉树\n");
else
printf("此二叉树不是完全二叉树\n");
return 0;
}
BiTree CreateTree()
{
BiTree root=NULL;
char x;
scanf("%c",&x);
if(x=='#')
{
root=NULL;
return root;
}
else
{
root=(BiTreeNode*)malloc(sizeof(BiTreeNode));
root->data=x;
root->lchild=CreateTree();
root->rchild=CreateTree();
}
return root;
}
void PreOrder(BiTree root)
{
if(root)
{
printf("%c",root->data);
PreOrder(root->lchild);
PreOrder(root->rchild);
}
}
void InOrder(BiTree root)
{
if(root)
{
InOrder(root->lchild);
printf("%c",root->data);
InOrder(root->rchild);
}
}
int leafnode(BiTree root)
{
if(root==NULL)
{
return 0;
}
else if(root->lchild==NULL&&root->rchild==NULL)
return 1;
else
{
return leafnode(root->lchild)+leafnode(root->rchild);
}
}
int highth(BiTree root)
{
if(root==NULL)
{
return 0;
}
else
if(highth(root->lchild)>highth(root->rchild))
{
return highth(root->lchild)+1;
}
else
return highth(root->rchild)+1;
}
int completetree(BiTree root)
{
BiTree sq[MAXSIZE];
int front=0,rear=0; //循环队列
BiTree p=root,q;
int flag=1;
rear=(rear+1)%MAXSIZE;
sq[rear]=p; //根结点入队
while(front!=rear) //队不为空队时
{
front=(front+1)%MAXSIZE;
q=sq[front];
if(q==NULL)
flag=0;
else
{
if(q!=NULL&&flag==0)
{
return 0;
}
rear=(rear+1)%MAXSIZE;
sq[rear]=q->lchild;
rear=(rear+1)%MAXSIZE;
sq[rear]=q->rchild;
}
}
return 1;
}