##L2-006. 树的遍历 ##
给定一棵二叉树的后序遍历和中序遍历,请你输出其层序遍历的序列。这里假设键值都是互不相等的正整数。
输入格式:
输入第一行给出一个正整数N(<=30),是二叉树中结点的个数。第二行给出其后序遍历序列。第三行给出其中序遍历序列。数字间以空格分隔。
输出格式:
在一行中输出该树的层序遍历的序列。数字间以1个空格分隔,行首尾不得有多余空格。
不解释题意(中文题),一道二叉树递归的基本操作。
基本思想为后序遍历最后输出根节点,接着在中序遍历中寻找根节点,找到根节点之后就能确实根节点的左右子树,接着在后序遍历寻找左右子树的根节点,这两个过程十分相似,可以用递归解决。
#include <iostream>
#include <string>
#include <cstring>
#include <iomanip>
#include <cmath>
#include <cstdlib>
#include <cstdio>
#include <algorithm>
#include <map>
#include <stack>
#include <queue>
#include <vector>
#include <set>
using namespace std;
#define ll long long
#define maxn 31
#define angel 0x3f3f3f3f
#define eps 1e-9
#define my_angel main
typedef struct TreeNode *tree;//指针表示二叉树
struct TreeNode
{
int element;
tree left,right;
};
int num[maxn];//后序遍历
int key[maxn];//中序遍历
tree makeTree(int now,int left,int right)//now为当前根节点
{
if(left>right)
return NULL;
int dir;
for(int i=left;i<=right;i++)//left,right为中序左(右)儿子的范围
{
if(num[now]==key[i])
{
dir=i;//中序遍历中找到根节点
break;
}
}
tree T=new TreeNode();
T->element=num[now];
T->right=makeTree(now-1,dir+1,right);//建立右儿子
T->left=makeTree(now-1-right+dir,left,dir-1);//建立左儿子
return T;
}
int my_angel()
{
int n;
scanf("%d",&n);
for(int i=1;i<=n;i++)
scanf("%d",&num[i]);
for(int i=1;i<=n;i++)
scanf("%d",&key[i]);
tree T=makeTree(n,1,n);//根节点
queue<tree>q;
q.push(T);
int p=0;
while(!q.empty())//层序遍历
{
tree now=q.front();
q.pop();
if(p++)
printf(" ");
printf("%d",now->element);
if(now->left!=NULL)
q.push(now->left);
if(now->right!=NULL)
q.push(now->right);
}
printf("\n");
return 0;
}