THU2015 fall 2-3 Rebuild
2015-11-05 10:12
369 查看
THU2015 fall 2-3 Rebuild
描述
某二叉树的n个节点已经用[1, n]内的整数进行了编号。现给定该二叉树的先序遍历序列和中序遍历序列,试输出其对应的后序遍历序列。
输入
第一行为一个数n。第二、三行,即已知的先序、中序遍历序列,数字之间以空格分隔。
输出
仅一行。若所给的先序、中续遍历序列的确对应于某棵二叉树,则输出其后序遍历序列,数字之间以空格分隔。否则,输出-1。
输入样例1
5 1 2 4 5 3 4 2 5 1 3
输出样例1
4 5 2 3 1
输入样例2
4 2 3 1 4 4 2 1 3
输出样例2
-1
输入样例3
8 5 2 4 1 3 6 7 8 4 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 500000 struct Node { Node *lchild, *rchild; int x; }Tree ; int loc; //int pro , mid ; 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; }
相关文章推荐
- ios Memory Usage Performance Guidelines
- JAVA笔记系列:字符串操作——string stringbuilder stringbuffer
- THU2015 fall 2-4 Queap
- SoapUI-传递 Respons header 中的值到 Request header
- Android 数据查询query函数参数解析
- UITextField,UITextView ,UILabel,键盘,UIFont
- Tsinghua OJ:真二叉树重构(Proper Rebuild)
- Builder
- 颜色转换 IOS中十六进制的颜色转换为UIColor
- Value Results,Not Just Effort
- easyUI,tree,获取一级子节点
- MUI-LIST列表的基本使用
- setRequestedOrientation
- UILabel ——千变万幻的文字
- easyui删除treegrid的行
- Win10 th2正式版Build 10586怎么更新升级?
- [LeetCode] Longest Increasing Subsequence 最长递增子序列
- *LeetCode-Longest Increasing Subsequence
- DuiLib DirectUI 界面库
- Android UI开发第二十四篇——Action Bar