二叉树的建立和基础操作<二> —— (层次遍历和计算二叉树的宽度)
2015-07-12 22:25
369 查看
考研进行时——二叉树的层次遍历和计算二叉树的宽度
/**********************
先序建立二叉树;
利用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;
}
树的原型是:
/**********************
先序建立二叉树;
利用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;
}
树的原型是:
相关文章推荐
- 今天没怎么学到东西。。。
- 核心动画 Core Animation
- sql 计算法定假节假日解决方案一
- 原创:各种normalize函数实现的性能和精度大比拼
- 二进制整数中的“1”
- 【转】解决Ubuntu下Sublime Text 3无法输入中文
- 复合模式Compound -- 学习HeadFirst设计模式记录
- django 1.8 官方文档翻译: 2-1-1 模型语法(初稿)
- Android PULL XML Praser
- Java基础全面解析——Java语言基础
- 老友重逢
- emacs使用multi-term作为terminal
- Python中的正则表达式
- 工业串口和网络软件通讯平台(SuperIO 2.1)更新发布
- 老友重逢
- Java基础全面解析——Java语言基础
- 要不断学习
- UIKit框架-04.UIButton
- Day13---TreeSet的使用
- 图论中的优先级搜索——DFS,BFS,Prim,Dijkstra