计算二叉树宽度——层次遍历
来源:互联网 发布:eview触摸屏软件 编辑:程序博客网 时间:2024/06/05 17:31
统计利用先序遍历创建的二叉树叶结点的个数(0973)
Time limit(ms): 1000
Memory limit(kb): 10000
Submission: 1268
Accepted: 862
Accepted
利用先序递归遍历算法创建二叉树并计算该二叉树叶结点的个数。先序递归遍历建立二叉树的方法为:按照先序递归遍历的思想将对二叉树结点的抽象访问具体化为根据接收的数据决定是否产生该结点从而实现创建该二叉树的二叉链表存储结构。约定二叉树结点数据为单个大写英文字符。当接收的数据是字符”#”时表示该结点不需要创建,否则创建该结点。最后再统计创建完成的二叉树叶结点的个数。需要注意输入数据序列中的”#”字符和非”#”字符的序列及个数关系,这会最终决定创建的二叉树的形态。
Description
接受键盘输入的由大写英文字符和”#”字符构成的一个字符串(用于创建对应的二叉树)。
Input
输出对应的二叉树叶结点的个数。
Output
1
2
3
4
5
6
7
8
#
A##
ABC####
AB##C##
ABCD###EF##G###
A##B##
#A
Sample Input
1
2
3
4
5
6
7
8
0
1
1
2
3
1
0
Sample Output
#include<stdio.h>
#include<stdlib.h>#include<queue>
#include<iostream>
using namespace std;
#define max(a,b) a>b?a:b
int i;
struct tree
{
char date;
struct tree *lchild;
struct tree *rchild;
};
#define len struct tree
int main()
{
void createtree(struct tree *&t,char str[]);
int width(struct tree *t);
struct tree *t;
char str[100];
while(scanf("%s",str)!=EOF)
{
i=0;
createtree(t,str);
printf("%d",width(t));
}
return 0;
}
void createtree(struct tree *&t,char str[])
{
if(str[i]!='#')
{
t=(len *)malloc(sizeof(len));
t->date=str[i];
i++;
createtree(t->lchild,str);
createtree(t->rchild,str);
}
else
{
t=NULL;
i++;
}
}
int width(struct tree *t)
{
if(t==NULL)
return 0;
int mx=0,cnt;
struct tree *p;
queue<struct tree *>queA,queB;//指针数组
queA.push(t);//元素入队
while(!queA.empty())//队不为空
{
cnt=0;
while(!queA.empty())
{
cnt++;
p=queA.front();
if(p->lchild!=NULL)
queB.push(p->lchild);
if(p->rchild!=NULL)
queB.push(p->rchild);
queA.pop();//元素出队
}
mx=max(mx,cnt);
queA=queB;
while(!queB.empty())
queB.pop();
}
return mx;
}
0 0
- 计算二叉树宽度——层次遍历
- 二叉树的建立和基础操作<二> —— (层次遍历和计算二叉树的宽度)
- 数据结构 — 5.二叉树层次遍历
- 数据结构—二叉树层次遍历
- 再谈二叉树的层次(宽度)遍历
- 层次遍历二叉树
- 层次遍历二叉树
- 二叉树层次遍历
- 二叉树 层次遍历
- 二叉树层次遍历
- 层次遍历二叉树
- 二叉树层次遍历
- 层次遍历二叉树
- 二叉树层次遍历
- 二叉树层次遍历
- 层次遍历二叉树
- 二叉树层次遍历
- 二叉树层次遍历
- android thread Interrupte使用方法
- “爱国者”连锁网络管理系统
- 设计模式:结构型模式:适配器(adapter)
- C++ 复制构造函数和赋值运算符重载函数
- Android编码规范风格指导(翻译)
- 计算二叉树宽度——层次遍历
- 4/28纪实——HCBA项目
- 在facebook上做app, 需要提交privacy policy url的解决办法
- android中EditText插入用户名(块)效果(EditText插入图片)
- [漏洞分析] BEdita CMS 3.5.0中存储型XSS与CSRF漏洞分析
- 2754: C++习题-快速排序
- 在main()之前,IAR都做了些什么工作
- 《佐贺的超级阿嬷》读后感
- Java知识(006)--数组