数据结构与算法问题 [NOIP2001]求先序排列
2014-09-13 18:08
295 查看
题目描述:
描述 Description
给出一棵二叉树的中序与后序排列。求出它的先序排列。(约定树结点用不同的大写字母表示,长度≤8)。
输入格式 Input Format
第一行为二叉树的中序序列
第二行为二叉树的后序序列
输出格式 Output Format
一行,为二叉树的先序序列
样例输入 Sample Input
BADCBDCA
样例输出 Sample Output
ABCD
描述 Description
给出一棵二叉树的中序与后序排列。求出它的先序排列。(约定树结点用不同的大写字母表示,长度≤8)。
输入格式 Input Format
第一行为二叉树的中序序列
第二行为二叉树的后序序列
输出格式 Output Format
一行,为二叉树的先序序列
样例输入 Sample Input
BADCBDCA
样例输出 Sample Output
ABCD
#include <iostream> #include <string> using namespace std; struct bitree { char data; bitree *lchild, *rchild; }; string inorder, postorder, ltree_inorder, rtree_inorder, ltree_postder, rtree_postder; int index1, index2; char rtree_first; void preorder(bitree *&root, string inorder, string postder, int lm, int rm, int lp, int rp) { root = new bitree; root->data = postorder[rp]; root->lchild = root->rchild = NULL; int pos = lm; while (inorder[pos] != postder[rp]) { pos++; } int lenl = pos - lm; //左树的长度 if (pos > lm) { preorder(root->lchild, inorder, postorder, lm, pos - 1, lp, lp + lenl - 1); } if (pos < rm) { preorder(root->rchild, inorder, postorder, pos + 1, rm, lp + lenl, rp - 1); } } void Preorder(bitree *&root) { if (root){ cout << root->data; Preorder(root->lchild); Preorder(root->rchild); } } int main() { bitree *root; cin >> inorder >> postorder; preorder(root, inorder, postorder, 0, inorder.size() - 1, 0, postorder.size() - 1); Preorder(root); system("pause"); }
相关文章推荐
- 恶补算法与数据结构(一)——排列问题
- 排列组合问题的通用算法
- 算法与数据结构:C语言的整数数组全排列(源码)
- 【树】[NOIP2001]求先序排列
- 微软等数据结构+算法面试100题(2)--给出一个函数来输出一个字符串的所有排列
- 【树】[NOIP2001]求先序排列
- 排列组合问题的通用算法
- 线性表13|约瑟夫问题 - 数据结构和算法18
- 求全排列问题的算法
- 算法与数据结构-背包问题
- 〖編程·C++〗回溯算法:排列树 - N皇后问题
- 数据结构:全排列的生成算法
- 数据结构研究之借连通性问题看算法设计
- 排列组合之排列问题的算法实现
- 【算法总结-排列组合与子集问题】排列组合与子集问题
- 题目:[NOIP2001]求先序排列
- 算法之排列问题
- 数据结构和算法设计(迷宫求解问题的栈和队列的实现)
- 排列组合问题的通用算法
- 线性表13|约瑟夫问题 - 数据结构和算法18