二叉树的建立和基础操作<二> —— (层次遍历和计算二叉树的宽度)

考研进行时——二叉树的层次遍历和计算二叉树的宽度

/**********************
先序建立二叉树; 
利用C++中的队列实现二叉树的层次遍历;
Width()函数返回二叉树的宽度 
*************************************************/
#include<iostream>
#include<queue> 
#include<stdio.h>
#include<stdlib.h>
using namespace std;
typedef char ElemType;
typedef struct BT
{
	ElemType data;
	struct BT *lch,*rch;
}BT,*BN;
BT * CreateBT()     
{
	BT *t;
	char c;
	scanf("%c",&c);
	if(c=='#')t=NULL;
	else
	{
	    t=(BT*)malloc(sizeof(BT));
        t->data=c;
        t->lch=CreateBT();
        t->rch=CreateBT();
	}
	return t;
}

void traverse(BN T)
{
	queue<BN> q;
	BN p=NULL;

	if(T)
		q.push(T);
	while(!q.empty())
	{
		
		p=q.front();
		q.pop();
		cout<<p->data<<" ";
		if(p->lch)
		{
			q.push(p->lch);
		}
		if(p->rch)
		{
			q.push(p->rch);
		}
	}
}

int Width(BT *T)
{
	if(T!=NULL)
	{
		if(T->lch==NULL&&T->rch==NULL)
		return 1;
		else
		return Width(T->lch)+Width(T->rch);
	}
}
int main()
{
	BT *T=NULL;
	printf("请输入要创建的树:");
	T=CreateBT();
    printf("\n层次遍历序列:\n");
	traverse(T); 
	printf("\n树的宽度是: ");
	printf("%d",Width(T));
   
	return 0;
}


树的原型是:


  • 3
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值