gplt L2-006. 树的遍历(后序中序求层序)
来源:互联网 发布:网络刷手一天能挣多少 编辑:程序博客网 时间:2024/05/22 10:23
https://www.patest.cn/contests/gplt/L2-006
题意:给出中序后序求层序。
思路:本来hdu1710已经模仿了别人代码了,考虑到前序后序也就顺序不同,没看资料自己改,就是通过后序找到根,然后用中序扩充嘛。
结果怎么也调不出来,下标应该已经对了啊,没道理啊。。结果前前后后调试一个多小时。。都快绝望了。。
。。。
居然是postorder[number-1]==inorder[i]这里的number必须是总元素数量不能改变。。
我宛若一个智障。。
#include <stdio.h>#include <algorithm>#include <string.h>#include <queue>#include <iostream>using namespace std;typedef long long ll;const int N = 35;typedef struct Tree{ Tree *left; Tree *right; int val;}Tree;Tree *root;int number;//代表元素数量int cnt;Tree* creat(int *postorder, int *inorder, int n)//前序、后序和子树长度{ Tree *tmp; for(int i = 0; i < n; i++) { if(postorder[number-1]==inorder[i])//在中序中找到这个根节点 { tmp = (Tree*)malloc(sizeof(Tree)); tmp->val = inorder[i]; tmp->left = creat(postorder-(n-i), inorder, i); tmp->right = creat(postorder-1, inorder+i+1, n-(i+1)); return tmp; } } return NULL;}void levelorder(Tree *cur){ cnt = 0; queue<Tree*>que; while(!que.empty()) que.pop(); que.push(cur); Tree *node; while(!que.empty()) { node = que.front(); que.pop(); if(cnt == number-1) printf("%d\n", node->val); else { printf("%d ", node->val); cnt++; } if(node->left != NULL) que.push(node->left); if(node->right != NULL) que.push(node->right); }}int main(){ // freopen("in.txt", "r", stdin); int postorder[N], inorder[N]; int n; while(~scanf("%d", &n)) { number = n; for(int i = 0; i < n; i++) scanf("%d", &postorder[i]); for(int i = 0; i < n; i++) scanf("%d", &inorder[i]); root = creat(postorder, inorder, n); levelorder(root); }}
0 0
- gplt L2-006. 树的遍历(后序中序求层序)
- GPLT L2-006. 树的遍历【递归建树+bfs输出】
- CCCC/GPLT L2-006 树的遍历
- L2-006. 树的遍历-PAT团体程序设计天梯赛GPLT
- gplt L2-011. 玩转二叉树(二叉树遍历)
- L2-006. 树的遍历
- L2-006. 树的遍历
- L2-006. 树的遍历
- L2-006. 树的遍历
- L2-006. 树的遍历
- L2-006. 树的遍历
- L2-006. 树的遍历
- L2-006. 树的遍历
- L2-006. 树的遍历
- L2-006. 树的遍历
- L2-006. 树的遍历
- L2-006. 树的遍历
- L2-006. 树的遍历
- Java项目中读取properties文件
- 【高性能JavaScript】读书笔记
- 【Spring MVC】深度探险SpringMVC(二)——框架介绍
- CSS单位
- ArrayList动态增长方式
- gplt L2-006. 树的遍历(后序中序求层序)
- 定位消耗CPU最多的线程
- TensorFlow用到的数学知识传送门
- className ~
- easyUI datagrid 遍历集合
- 关联规则算法1------关联规则Apriori原理和R实现
- 事务的四种隔离级别
- dpdk学习之一--初识dpdk
- hessian构建RPC的两种方式