您的位置:首页 > 其它

[codevs]模板-二叉树基础

2016-04-22 23:31 204 查看
1501 二叉树最大宽度和高度

时间限制: 1 s

空间限制: 128000 KB

题目等级 : 白银 Silver

题解

题目描述 Description

给出一个二叉树,输出它的最大宽度和高度。

输入描述 Input Description

第一行一个整数n。

下面n行每行有两个数,对于第i行的两个数,代表编号为i的节点所连接的两个左右儿子的编号。如果没有某个儿子为空,则为0。

输出描述 Output Description

输出共一行,输出二叉树的最大宽度和高度,用一个空格隔开。

样例输入 Sample Input

5

2 3

4 5

0 0

0 0

0 0

样例输出 Sample Output

2 3

数据范围及提示 Data Size & Hint

n<16

默认第一个是根节点

以输入的次序为编号

2-N+1行指的是这个节点的左孩子和右孩子

这里写代码片#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
using namespace std;

struct tree{
int l,r;
}l[2333];

int tong[2333];

int maxw = 0,maxdeep = 0;

void dfs(int p,int d)
{
if(p == 0) return ;
tong[d] ++;
maxdeep = max(d,maxdeep);
maxw = max(maxw,tong[d]);
dfs(l[p].l,d + 1);
dfs(l[p].r,d + 1);
}

int main()
{
int n;
scanf("%d",&n);
for(int i = 1;i <= n;i ++)
{
scanf("%d%d",&l[i].l,&l[i].r);
}
dfs(1,1);
printf("%d %d",maxw,maxdeep);
return 0;
}


3143 二叉树的序遍历

时间限制: 1 s

空间限制: 32000 KB

题目等级 : 白银 Silver

题解

题目描述 Description

求一棵二叉树的前序遍历,中序遍历和后序遍历

输入描述 Input Description

第一行一个整数n,表示这棵树的节点个数。

接下来n行每行2个整数L和R。第i行的两个整数Li和Ri代表编号为i的节点的左儿子编号和右儿子编号。

输出描述 Output Description

输出一共三行,分别为前序遍历,中序遍历和后序遍历。编号之间用空格隔开。

样例输入 Sample Input

5

2 3

4 5

0 0

0 0

0 0

样例输出 Sample Output

1 2 4 5 3

4 2 5 1 3

4 5 2 3 1

数据范围及提示 Data Size & Hint

n <= 16

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int M = 20;

struct dot
{
int l,r;
}tree[M];

void qian(int x)
{
printf("%d ",x);
if(tree[x].l)
qian(tree[x].l);
if(tree[x].r)
qian(tree[x].r);
return;
}

void zhong(int x)
{
if(tree[x].l)
zhong(tree[x].l);
printf("%d ",x);
if(tree[x].r)
zhong(tree[x].r);
return;
}

void hou(int x)
{
if(tree[x].l)
hou(tree[x].l);
if(tree[x].r)
hou(tree[x].r);
printf("%d ",x);
return;
}

int main()
{
int n;
scanf("%d",&n);
for(int i=1; i<=n; i++)
scanf("%d%d",&tree[i].l,&tree[i].r);
qian(1);
printf("\n");
zhong(1);
printf("\n");
hou(1);
printf("\n");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: