问题链接:https://pintia.cn/problem-sets/994805342720868352/problems/994805485033603072
Note:
1 新建结点的格式不能错,不能用=NULL;
node *root = new node; //新建一个新的结点,用来存放当前二叉树的根节点
2 队列中存的是结点地址,所以是<node*> 而不是<node>
queue<node*> Q; //队列中存结点地址
3 注意代码中num的用法,用于控制是否输出空格(最后一个数后不输出)
if(num < n)//输出的结点数小于总结点数
cout << " ";
#include<cstdio>
#include<iostream>
#include<queue>
#include<algorithm>
using namespace std;
const int maxn = 50;
struct node{
int data;
node *lchild;
node *rchild;
};//树结点
int in[maxn], post[maxn];//存储先序,中序,后序遍历
int n; //结点个数
//当前二叉树的后序序列区间为 [postL,postR] 中序序列区间为 [inL,inR]
//create函数返回构建出的二叉树的根节点地址
node *create(int postL, int postR, int inL, int inR){
if(postL > postR)
return NULL;
node *root = new node; //新建一个新的结点,用来存放当前二叉树的根节点
root -> data = post[postR];//新结点的数据域为根节点的值
int k;//在中序序列中找到in[k] == pre[L]的结点,k存放该结点在中序遍历的位置
for(k = inL; k <= inR; k++)
if(in[k] == post[postR])
break;
int numLeft = k - inL; //左子树的结点个数
root -> lchild = create(postL, postL + numLeft - 1, inL, k - 1);
root -> rchild = create(postL + numLeft, postR - 1, k + 1, inR);
return root;
}
int num = 0; //已输出的结点数
void level(node *root)//层序遍历
{
queue<node*> Q; //队列中存结点地址
Q.push(root); //将根节点地址入队
while(!Q.empty()){
node *p = Q.front();
cout << p -> data;
Q.pop();
num++;
if(num < n)//输出的结点数小于总结点数
cout << " ";
if(p -> lchild != NULL)
Q.push(p -> lchild);
if(p -> rchild != NULL)
Q.push(p -> rchild);
}
}
int main(){
cin >> n;//输入总结点数
for(int i = 0; i < n; i++)
cin >> post[i];
for(int i = 0; i < n; i++)
cin >> in[i];
node *root = create(0, n-1, 0, n-1);//建树
level(root); //层序遍历输出
return 0;
}