首页 技术 正文
技术 2022年11月18日
0 收藏 645 点赞 4,098 浏览 1848 个字

Suppose that all the keys in a binary tree are distinct positive integers. Given the postorder and inorder traversal sequences, you are supposed to output the level order traversal sequence of the corresponding binary tree.

Input Specification:

Each input file contains one test case. For each case, the first line gives a positive integer N (≤), the total number of nodes in the binary tree. The second line gives the postorder sequence and the third line gives the inorder sequence. All the numbers in a line are separated by a space.

Output Specification:

For each test case, print in one line the level order traversal sequence of the corresponding binary tree. All the numbers in a line must be separated by exactly one space, and there must be no extra space at the end of the line.

Sample Input:

7
2 3 1 5 7 6 4
1 2 3 4 5 6 7

Sample Output:

4 1 6 3 5 7 2
 #include<cstdio>
#include<queue>
using namespace std;
int post[],in[];
struct node{
int data;
node *lchild;
node *rchild;
};
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;
for(k=inL;k<=inR;k++){
if(post[postR]==in[k]){
break;
}
}
int numleft=k-inL;
root->lchild=create(postL,postL+numleft-,inL,k-);//这里经常出错
root->rchild=create(postL+numleft,postR-,k+,inR);
return root;
}
void LayerOrder(node*root,int k){
if(root==NULL){
return;
}
queue<node*> q;
q.push(root);
while(!q.empty()){
node *now=q.front();
q.pop();
if(k!=){
printf("%d ",now->data);
k--;
}else{
printf("%d",now->data);
}
if(now->lchild!=NULL){
q.push(now->lchild);
}
if(now->rchild!=NULL){
q.push(now->rchild);
}
}
}
int main(){
int n;
scanf("%d",&n);
for(int i=;i<n;i++){
scanf("%d",&post[i]);
}
for(int i=;i<n;i++){
scanf("%d",&in[i]);
}
node *p=create(,n-,,n-);
LayerOrder(p,n);
return ;
}

Mist Note: 解决本题,本小编的思路是,先利用中序和后序序列重建二叉树,然后再层序遍历这棵树。

很多算法还是基础的,主要是在递归重建那里经常出问题。左子树和右子树的递归。

root->lchild=create(postL,postL+numleft-1,inL,k-);

root->rchild=create(postL+numleft,postR-,k+,inR);

红色部分经常出错,切记,我们在写代码的时候,经常是利用数组,而数组是以0开始的,而numleft是个数,你加之后,肯定需要-1,才符合定义,不要混淆。

本题还需要注意输出格式,最后层序遍历的最后一个节点,是不需要空格的。

 
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,022
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,513
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,359
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,142
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,773
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,851