THU2015 fall 2-3 Rebuild
来源:互联网 发布:程序员黄历 安卓 编辑:程序博客网 时间:2024/04/30 12:10
THU2015 fall 2-3 Rebuild
描述
某二叉树的n个节点已经用[1, n]内的整数进行了编号。现给定该二叉树的先序遍历序列和中序遍历序列,试输出其对应的后序遍历序列。
输入
第一行为一个数n。
第二、三行,即已知的先序、中序遍历序列,数字之间以空格分隔。
输出
仅一行。
若所给的先序、中续遍历序列的确对应于某棵二叉树,则输出其后序遍历序列,数字之间以空格分隔。否则,输出-1。
输入样例1
51 2 4 5 34 2 5 1 3
输出样例1
4 5 2 3 1
输入样例2
42 3 1 44 2 1 3
输出样例2
-1
输入样例3
85 2 4 1 3 6 7 84 2 1 5 3 7 6 8
输出样例3
4 1 2 7 8 6 3 5
限制
1 <= n <= 500,000,n为整数
输入和输出的遍历序列均为[1, n]内整数的一个排列,整数间均以空格分隔。
时间:1sec
空间:256MB
代码如下:
#include <stdio.h>#include <stdlib.h>const int SZ = 1 << 20; //提升IO buff struct fastio{char inbuf[SZ];char outbuf[SZ];fastio(){setvbuf(stdin, inbuf, _IOFBF, SZ);setvbuf(stdout, outbuf, _IOFBF, SZ);}}io;#define N 500000struct Node{Node *lchild, *rchild;int x;}Tree[N];int loc;//int pro[N], mid[N];int count = 0;Node *create(){Tree[loc].lchild = Tree[loc].rchild = NULL;return &Tree[loc++];}Node *buildTree(int *pro, int *mid, int x1, int y1, int x2, int y2){Node *root = create();root->x = pro[x1];int loc_root;int flag = 1;for (int i = x2; i <= y2; i++)if (mid[i] == pro[x1]) //寻找树根结点在中序序列中的位置{loc_root = i;flag = 0;count++;break;}if (flag) return NULL;if (loc_root != x2)root->lchild = buildTree(pro, mid, x1 + 1, x1 + loc_root - x2, x2, loc_root - 1);if (loc_root != y2)root->rchild = buildTree(pro, mid, x1 + loc_root - x2 + 1, y1, loc_root + 1, y2);return root;}void postOrder(Node *Tree){if (Tree->lchild != NULL) postOrder(Tree->lchild);if (Tree->rchild != NULL) postOrder(Tree->rchild);printf("%d ", Tree->x);}int main(){int n;scanf("%d", &n);int *pro = (int *)malloc((n + 1) * sizeof(int));int *mid = (int *)malloc((n + 1) * sizeof(int));for (int i = 0; i < n; i++)scanf("%d", pro + i);for (int i = 0; i < n; i++)scanf("%d", mid + i);Node *Tree = buildTree(pro, mid, 0, n-1, 0, n-1);if (count != n) printf("-1");else postOrder(Tree);printf("\n");//system("pause");free(pro);free(mid);return 0;}
0 0
- THU2015 fall 2-3 Rebuild
- THU2015 fall 2-2 Train
- THU2015 fall 1-3 Interview
- THU2015 fall 2-4 Queap
- THU2015 fall 1-2 Company
- THU2015 fall 1-1 Team
- 2017 Fall SoftwareEngineering Learning (3)
- 2017 Fall SoftwareEngineering Learning (2)
- CS193p 2013 Fall Lecture 2 notes
- Fall Regimen
- rebuild 和rebuild online
- note: please rebuild precompiled header ..... /UIKit-2DYE2I2D1B3GL.pcm 解决方案
- rebuild index
- rebuild controlfile
- dissect rebuild
- index rebuild
- hdu5531 Rebuild
- hdu5531 Rebuild
- JNI用法参考
- GCD
- ios Memory Usage Performance Guidelines
- 绪论
- JAVA笔记系列:字符串操作——string stringbuilder stringbuffer
- THU2015 fall 2-3 Rebuild
- JNI中打印日志
- setsockopt说明
- 用putty登录ubuntu系统
- 在命令行输入matlab,将matlab启动
- error while loading shared libraries
- andorid之tab+fragment的使用及结合viewpager,滑动时候重新oncreateView的优化
- Annotation
- 使用Linux的Crontab定时执行PHP脚本