L2-011. 玩转二叉树
来源:互联网 发布:双三次插值算法 编辑:程序博客网 时间:2024/06/14 08:55
给定一棵二叉树的中序遍历和前序遍历,请你先将树做个镜面反转,再输出反转后的层序遍历的序列。所谓镜面反转,是指将所有非叶结点的左右孩子对换。这里假设键值都是互不相等的正整数。
输入格式:
输入第一行给出一个正整数N(<=30),是二叉树中结点的个数。第二行给出其中序遍历序列。第三行给出其前序遍历序列。数字间以空格分隔。
输出格式:
在一行中输出该树反转后的层序遍历的序列。数字间以1个空格分隔,行首尾不得有多余空格。
输入样例:71 2 3 4 5 6 74 1 3 2 6 5 7输出样例:
4 6 1 7 5 3 2
#include<cstdio>#include<iostream>#include<vector> #include<queue>using namespace std;int pre[40],in[30];struct node{int num;struct node* left;struct node* right;}; struct node*build(int p1,int p2,int i1,int i2){if(p1>p2||i1>i2)return NULL;int p;for(int i=i1;i<=i2;i++){if(in[i]==pre[p1]){p=i;break;}}struct node* root=new node();root->num=in[p];root->left=build(p1+1,p1+p-i1,i1,p-1);root->right=build(p1+p-i1+1,p2,p+1,i2);return root; }queue<struct node*>q;vector<int>vec;void bfs(struct node * root){q.push(root);while(!q.empty()){node* tmp=q.front();q.pop();vec.push_back(tmp->num);if(tmp->right)q.push(tmp->right);if(tmp->left)q.push(tmp->left);}}int main(){int n;scanf("%d",&n);for(int i=0;i<n;i++){scanf("%d",&in[i]);}for(int i=0;i<n;i++){scanf("%d",&pre[i]);}struct node*root=NULL;root=build(0,n-1,0,n-1);bfs(root);for(int i=0;i<vec.size()-1;i++){printf("%d ",vec[i]);}printf("%d\n",vec[vec.size()-1]);return 0;}
阅读全文
0 0
- L2-011. 玩转二叉树
- L2-011. 玩转二叉树
- L2-011. 玩转二叉树
- PAT L2-011. 玩转二叉树
- L2-011. 玩转二叉树
- L2-011. 玩转二叉树
- L2-011. 玩转二叉树
- pat L2-011. 玩转二叉树@
- L2-011. 玩转二叉树
- L2-011. 玩转二叉树
- L2-011. 玩转二叉树
- L2-011. 玩转二叉树
- L2-011. 玩转二叉树
- L2-011. 玩转二叉树
- L2-011. 玩转二叉树
- L2-011. 玩转二叉树
- PAT L2-011. 玩转二叉树
- L2-011. 玩转二叉树
- 存储过程跨用户执行execute immediate权限不足
- 实现Imageview两个圆角的效果
- 初识java后台
- poj 1321 棋盘问题(Dfs)
- hdu2072-单词数 字典树、STL
- L2-011. 玩转二叉树
- 长连接转短链接
- 组合数
- Android几种进程
- 剑指offer--反转链表
- POJ Remmarguts' Date A*搜索+spfa
- 如何解决WebBrowser.DocumentCompleted事件的多次调用
- JS高级程序设计——BOM
- Python3网络爬虫(十三):王者荣耀那些事!(Fiddler之手机APP爬取)