计算二叉树宽度——层次遍历

来源:互联网 发布: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
原创粉丝点击