HDU 1710 Binary Tree Traversals(已知先序中序求后序)
2016-03-05 15:14
381 查看
题目链接:【HDU 1710】
输入先序遍历跟中序遍历,输出后序遍历
输入先序遍历跟中序遍历,输出后序遍历
#include <iostream> #include <algorithm> #include <cstdio> #include <cstring> #include <string> using namespace std; const int N=1010; struct node { int v; node *left , *right; node():left(NULL),right(NULL){} //默认值 }; node* root; void remove_tree(node* u) { if(u==NULL) return; remove_tree(u->left); remove_tree(u->right); delete u; } node* newnode() { return new node; } node *create_tree(int* a, int* b , int n) { node* u=newnode();//创建一个新的节点 for(int i=0; i<n; i++) { if(a[0]==b[i]) //中序遍历时的根节点 { u->v = a[0]; u->left=create_tree(a+1, b, i); u->right=create_tree(a+i+1, b+i+1, n-i-1); return u; } } return NULL; } void output(node* u)//输出后序遍历 { if(u==NULL) return; output(u->left); output(u->right); if(u==root) printf("%d\n", root->v); else printf("%d ", u->v); } int main() { int n; int a , b ; while(~scanf("%d", &n)) { for(int i=0; i<n; i++) scanf("%d", &a[i]); for(int i=0; i<n; i++) scanf("%d", &b[i]); remove_tree(root);//清空树 root = create_tree(a, b, n); output(root); } return 0; } /* 9 1 2 4 7 3 5 8 9 6 4 7 2 1 8 5 9 3 6 */
相关文章推荐
- 数组实现stack
- 利用shell脚本重启node.js
- C++设计模式之适配器模式
- 环境变量-Linux
- CodeBlocks去掉拼写检查
- 复杂链表的复制
- VS2010 VS2012版最常用的快捷键
- JAVA设计模式之适配器模式
- 面试题
- 自己动手写CPU之第七阶段(7)——乘累加指令的实现
- 第二次作业
- jquery()的三种$()
- eclipse中egit插件使用
- You need to use a Theme.AppCompat theme (or descendant) with this activity.
- iOS 集合的深复制与浅复制
- 单例整理
- iOS 证书设置总是信任
- HDU 2181 哈密顿绕行世界问题
- ThinkPHP - 模型
- 在centos中如何用yum安装最新的yum源