数据结构:二叉树的应用

算法设计:

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;
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值