题目:
给定一棵二叉树的后序遍历和中序遍历,请你输出其层序遍历的序列。这里假设键值都是互不相等的正整数。
输入格式:
输入第一行给出一个正整数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<cstring>
#include<queue>
using namespace std;
typedef struct node{//通过结构体定义树的节点
int data;//记录节点数据
struct node *left,*right;//左右孩子
}*Tree;
int post[35],in[35];
Tree build_Tree(int post[],int in[],int n)
{
if(n == 0) return NULL;
Tree root = (Tree)malloc(sizeof(Tree));
root -> data = post[n - 1];
int i;
for(i = 0;i < n;i++){
if(in[i] == post[n - 1]) break;
}
root -> left = build_Tree(post,in,i);
root -> right = build_Tree(post + i,in + i + 1,n - 1 - i);
return root;
}
void levelprint(Tree root)//层序遍历
{
if(root == NULL) return;
int temp = 0;
queue<Tree> q;
q.push(root);
while(!q.empty())
{
Tree t = q.front();
q.pop();
if(temp == 0){
cout<<t -> data;
temp = 1;
}
else cout<<" "<<t -> data;
if(t -> left) q.push(t -> left);
if(t -> right) q.push(t -> right);
}
}
int main()
{
int n;
cin>>n;
for(int i = 0;i < n;i++){
cin>>post[i];//后序
}
for(int i = 0;i < n;i++){
cin>>in[i];//中序
}
Tree root = build_Tree(post,in,n);
levelprint(root);
return 0;
}