解题思路:
不管是左右子树还是整棵树,后序遍历的最后一个元素就是根节点,然后从中序遍历中找到根节点在中序遍历的位置,并且记录左子树元素的个数。
中序遍历中根节点以前的位左子树,以后的位右子树,然后递归遍建立左右子树,如果子树为空则返回0,l>r的情况就是子树为空的情况。在根据根节点输出层序遍历就可以了。
#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
#define N 35
int last[N],in[N];
struct node{
int left;
int right;
}tree[N];
int n,cnt;
int build(int l1,int r1,int l2,int r2){
int root;
if(l1 <= r1&&l2 <= r2){
root = last[r2];
int cnt = 0;
int index;
for(index = l1;in[index] != root;index++,cnt++);//判定根节点下标和确定左子树的元素个数
tree[root].left = build(l1,index-1,l2,l2+cnt-1);//建立左子树
tree[root].right = build(index+1,r1,l2+cnt,r2-1);//建立右子树
}else{
return 0;
}
return root;
}
void print(int root){
queue<int>q;
q.push(root);//根节点入队
while(!q.empty()){
int temp = q.front();
cnt++;
printf("%d",temp);//输出结点
if(cnt != n){
printf(" ");
}else{
printf("\n");
}
q.pop();
if(tree[temp].left){
q.push(tree[temp].left);//左子树如队列
}
if(tree[temp].right){
q.push(tree[temp].right);//右子树入队列
}
}
}
int main(){
// freopen("input.txt","r",stdin);
scanf("%d",&n);
for(int i = 1;i <= n;i++){
scanf("%d",&last[i]);
}
for(int i = 1;i <= n;i++){
scanf("%d",&in[i]);
}
int root = build(1,n,1,n);
print(root);
return 0;
}
本文介绍了一种通过后序遍历和中序遍历构建二叉树的方法,并实现了层序遍历输出构建后的二叉树。首先,从后序遍历中找到根节点,再从中序遍历中定位该根节点,以此划分左右子树,递归建立整棵树。最后采用队列实现层序遍历。

166

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



