您的位置:首页 > 其它

PAT - 团体程序设计天梯赛-练习集 - L2-006 - 树的遍历

2017-03-22 15:42 295 查看
Problem : 树的遍历

Descritption :

给定一棵二叉树的后序遍历和中序遍历,请你输出其层序遍历的序列。这里假设键值都是互不相等的正整数。

Solution :

后序遍历的特点就是序列最后一个元素是根,其余的部分连续是左子树和右子树;中序遍历的特点就是序列的中间某个是根,左右分别是其左右子树。我们根据这两个特点,利用后序遍历序列中的根在中序遍历序列中查找,得出其左右子树的规模,用这个规模在后序遍历序列中继续划分递归!利用bfs队列的方式可以得出层序遍历。

Code (C++) :

#include <stdio.h>
#include <string.h>

#define MAX_LINE 35

typedef struct tagNode {
int src, des;
int s, d;
tagNode() {}
tagNode(int src, int des, int s, int d) : src(src), des(des), s(s), d(d) {}
}Node;

int n;
int next[MAX_LINE], mid[MAX_LINE];

Node que[MAX_LINE * MAX_LINE];
int head, tail;

int find_root(int x, int s, int d)
{
for (int i = s; i <= d; i++)
if (x == mid[i])
return i;
return -1;
}

int main()
{
//freopen("in", "r", stdin);
while (~scanf("%d", &n)) {
for (int i = 0; i < n; i++)
scanf("%d", &next[i]);
for (int i = 0; i < n; i++)
scanf("%d", &mid[i]);
head = tail = 0;

que[tail++] = Node(0, n - 1, 0, n - 1);
while (tail != head) {
Node pre = que[head++];
int root_pos = find_root(next[pre.des], pre.s, pre.d);
int m = pre.d - root_pos;
m = pre.des - 1 - m;
if (pre.src <= m)
que[tail++] = Node(pre.src, m, pre.s, root_pos - 1);
if (m + 1 <= pre.des - 1)
que[tail++] = Node(m + 1, pre.des - 1, root_pos + 1, pre.d);
}
for (int i = 0; i < tail; i++)
printf("%d%c", next[que[i].des], i == tail - 1 ? '\n' : ' ');
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: