pat L2-006-已知二叉树的后序序列和中序序列求层序遍历结果

L2-006. 树的遍历

时间限制
400 ms
内存限制
65536 kB
代码长度限制
8000 B
判题程序
Standard
作者
陈越

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

输入格式:

输入第一行给出一个正整数N(<=30),是二叉树中结点的个数。第二行给出其后序遍历序列。第三行给出其中序遍历序列。数字间以空格分隔。

输出格式:

在一行中输出该树的层序遍历的序列。数字间以1个空格分隔,行首尾不得有多余空格。

输入样例:
7
2 3 1 5 7 6 4
1 2 3 4 5 6 7
输出样例:
4 1 6 3 5 7 2

#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
#include<vector>
#include<climits>


using namespace std;


struct Node{
int r;
int l;
};


int be[35],mid[35],N;
Node tree[35];


int build(int lb,int rb, int lm, int rm)//lb,rb代表后序序列的最左端和最右端,lm,rm代表中序序列最左端和最右端 
{
//注意递归停止条件,否则会无限递归下去 
if(lb > rb) //当等于0时表示该根没有子节点 
return 0;
//后序遍历的最后一个元素一定为这棵树的根
int root = be[rb],x,y;
//在中序遍历中找到根 
x = lm; 
while(mid[x] != root) x++;
y = x - lm;
//确定根在第几个位置,再分成两边递归寻找根的左右节点 
tree[root].l = build(lb,lb+y-1,lm,x-1);
tree[root].r = build(lb+y,rb-1,x+1,rm); 
//返回具体的数字代表具体的节点 
return root;
}


void BFS(int root)
{
queue<int> q;
vector<int> v;
q.push(root);
while(!q.empty())
{
int temp = q.front();
q.pop();
v.push_back(temp);
if(tree[temp].l != 0)
q.push(tree[temp].l);
if(tree[temp].r != 0)
q.push(tree[temp].r);
}
int len = v.size(); 
for(int i = 0; i < len-1; i++)
cout<<v[i]<<" ";
cout<<v[len-1]<<endl;
}

int main()
{
scanf("%d",&N);
for(int i = 0; i < N; i++) scanf("%d",&be[i]);
for(int i = 0; i < N; i++) scanf("%d",&mid[i]);
build(0,N-1,0,N-1);
BFS(be[N-1]);

 return 0;

}

此题还有更简单的做法:此博客->https://blog.csdn.net/qq_34594236/article/details/63273098

猜你喜欢

转载自blog.csdn.net/cutedumpling/article/details/79718927