A1020 Tree Traversals (25 分)
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,才符合定义,不要混淆。
本题还需要注意输出格式,最后层序遍历的最后一个节点,是不需要空格的。
最新文章
- 在Eclipse中使用Git
- java中scanner类的用法
- android studio没有org.apache.http.client.HttpClient;等包问题 解决方案
- JVM生产环境参数实例及分析
- Codeforces 627 A. XOR Equation (数学)
- Android 设置ListView不可滚动 及在ScrollView中不可滚动的设置
- html 标签的嵌套规则
- 感觉tbceditor很不错,如果作者能坚持下来,非常非常看好啊
- Hadoop集群配置(最全面总结)
- dfs+剪枝:poj2362
- 基于.NET的弹性及瞬间错误处理库Polly
- Material Design之NavigationView和DrawerLayout实现侧滑菜单栏
- Mybaits-plus实战(一)
- Python字符编码的发展、cmd寻找路径
- PHP之获取终端用户IP
- yum 安装报错:Could not retrieve mirrorlist http://mirrorlist.centos.org/?release=7&;arch=x86_64&;repo=os&;infra=stock error was 14: curl#6 - ";Could not resolve host: mirrorlist.centos.org; Unknown error";
- EF 多线程TransactionScope事务异常";事务EFTransaction类定义:与另一个进程被死锁在 锁 资源上,并且已被选作死锁牺牲品。请重新运行该事务。";
- tcp五层模型
- MySQL 查询结果分组 group by
- HDU 4372 - Count the Buildings(组合计数)