L2-006 树的遍历
给定一棵二叉树的后序遍历和中序遍历,请你输出其层序遍历的序列。这里假设键值都是互不相等的正整数。
输入格式:
输入第一行给出一个正整数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
思路:
该题目主要是根据树的后序遍历与中序遍历建树。其中后序遍历区间的最后一个元素为当前区间的根节点,用中序遍历可以在后序遍历中分别出左子树与右子树。再不断的向下递归缩区间即可
AC代码:
#include<bits/stdc++.h>
using namespace std;
struct node{
int val;
node *ln;
node *rn;
};
int n;
int num = 0;
const int maxn = 35;
int post[maxn];
int in[maxn];
node * creat(int pos,int poe,int ins,int ine){
if(pos>poe)
return NULL;
node * root = new node;
root->val = post[poe];
int i;
for(i = ins;i<=ine;i++){
if(in[i]==post[poe])
break;
}
int trleft = i - ins; //trleft用于将左子树与右子树分开
root->ln = creat(pos,pos+trleft-1,ins,i-1);
root->rn = creat(pos+trleft,poe-1,i+1,ine);
return root;
}
void bfs(node* root){
queue<node*> q;
q.push(root);
while(!q.empty()){
node* p = q.front();
q.pop();
num++;
cout<<p->val;
if(num<n) cout<<" ";
if(p->ln!=NULL) q.push(p->ln);
if(p->rn!=NULL) q.push(p->rn);
}
}
int main(void){
cin>>n;
for(int i=0;i<n;i++){
cin>>post[i];
}
for(int i=0;i<n;i++){
cin>>in[i];
}
node * root = creat(0,n-1,0,n-1);
bfs(root);
return 0;
}
本文介绍了一种根据二叉树的后序遍历和中序遍历序列,构建二叉树并输出其层序遍历序列的方法。通过递归算法创建树结构,并使用队列实现层序遍历,最后输出遍历结果。
1204

被折叠的 条评论
为什么被折叠?



