树的遍历
题目描述:
给定一棵二叉树的后序遍历和中序遍历,请你输出其层序遍历的序列。
这里假设键值都是互不相等的正整数。
Input:
输入第一行给出一个正整数N(≤30),是二叉树中结点的个数。
第二行给出其后序遍历序列。第三行给出其中序遍历序列。数字
间以空格分隔。
Output:
在一行中输出该树的层序遍历的序列。数字间以1个空格分隔,
行首尾不得有多余空格。
Sample Input:
7
2 3 1 5 7 6 4
1 2 3 4 5 6 7
Sample Output:
4 1 6 3 5 7 2
二叉树遍历:
这道题考的是二叉树的遍历问题,先讲这道题思路前,先讲一下二叉树的
四种基础遍历:
1. 前序遍历:根节点->左子点->右子点,这个序列特点在于他的根
永远在第一位。
2. 中序遍历:左节点->根节点->右节点,这个序列特点在于只要找
出根的位置,就能划分左右子树。
3. 后序遍历:左节点->右节点->根节点,这个序列特点在于他的根
永远在最后一位。
4. 层序遍历:这个遍历是每一层从左到右开始遍历,遍历完第一层
就到下一层,他的遍历可以用队列结构,因为满足先进后出的特点。
思路分析:
思路分析:这道题给出了后序与中序的遍历顺序以及节点数,这道题可以用
递归或者链表去写,这里先讲递归的思路,递归的思路相当于:用DFS的方
式去找出左右子树的节点,这里需要判断边界和递归条件以及根的位置,那
么我们知道了后序遍历。
1. 判断边界:只要递归的时候,他所递归的值不要超过后序与中序区间
就可以了。
2. 找根节点:这里因为有后序,那么根一定在后序的最后一个点,按照
这个条件递归就可以了。
3. 递归条件:这里具体看代码注释,结合代码和注释才容易理解
代码:
#include<queue>
#include<cstdio>
#include<iostream>
#include<stack>
#include<map>
#include<set>
#include<algorithm>
#include<vector>
#include<cmath>
using namespace std;
int b[40],a[40];
map<int,int>R,L;
int LemonCreatTree(int m,int n,int d,int f)
{
int i;
if(m>n)
{
return 0;
}
int root=b[n];
int p=0,num;
for(num=d;num<=f;num++)
{
if(a[num]!=root)
{
p++;
}
else
break;
}
R[root]=LemonCreatTree(m+p,n-1,num+1,f);
L[root]=LemonCreatTree(m,m+p-1,d,num-1);
return root;
}
void LemonBFS(int root)
{
queue<int>q;
q.push(root);
int cnt=0;
while(!q.empty())
{
int n=q.front();
q.pop();
printf(cnt++==0?"%d":" %d",n);
if(L[n])
{
q.push(L[n]);
}
if(R[n])
{
q.push(R[n]);
}
}
}
int main()
{
int d;
scanf("%d",&d);
for(int i=1;i<=d;i++)
{
scanf("%d",&b[i]);
}
for(int i=1;i<=d;i++)
{
scanf("%d",&a[i]);
}
int root=LemonCreatTree(1,d,1,d);
LemonBFS(root);
}