由二叉树中序遍历和先序遍历,构造二叉树,经过镜面翻转后输出层次遍历结果
来源:互联网 发布:如何让淘宝导航条全屏 编辑:程序博客网 时间:2024/05/16 19:32
玩转二叉树
给定一棵二叉树的中序遍历和前序遍历,请你先将树做个镜面反转,再输出反转后的层序遍历的序列。所谓镜面反转,是指将所有非叶结点的左右孩子对换。这里假设键值都是互不相等的正整数。
输入格式:
输入第一行给出一个正整数N
(≤30),是二叉树中结点的个数。第二行给出其中序遍历序列。第三行给出其前序遍历序列。数字间以空格分隔。
输出格式:
在一行中输出该树反转后的层序遍历的序列。数字间以1个空格分隔,行首尾不得有多余空格。
输入样例:
71 2 3 4 5 6 74 1 3 2 6 5 7
输出样例:
4 6 1 7 5 3 2
题目地址:https://www.patest.cn/contests/gplt/L2-011
#include <iostream>#include <cstdio>#include <cmath>#include <queue>#include <stack>#include <map>#include <algorithm>#include <vector>#include <string>#include <cstring>#include <sstream>using namespace std;struct Btree{ int data; Btree* left; Btree* right;};typedef struct Btree Btree;int zhong[100];int xian[100];int n;int Find(int *zhong,int x,int len){ for(int i=0;i<len;i++) { if(zhong[i]==x) { return i; } }}Btree* build(int *zhong,int *xian,int len){ if(len<=0) return NULL; Btree *tmp=new Btree; tmp->data=xian[0]; int index=Find(zhong,xian[0],len); tmp->left=build(zhong,xian+1,index); tmp->right=build(zhong+index+1,xian+index+1,len-index-1); return tmp;}void Reverse(Btree *root){ if(root==NULL) return; Reverse(root->left); Reverse(root->right); Btree *tmp=root->left; root->left=root->right; root->right=tmp;}int ans[100];int cur;queue<Btree*> Q;void CenOrder(Btree *root){ Q.push(root); while(!Q.empty()) { Btree *tmp=Q.front(); Q.pop(); ans[cur++]=tmp->data; if(tmp->left) { Q.push(tmp->left); } if(tmp->right) { Q.push(tmp->right); } }}int main(){ scanf("%d",&n); for(int i=0;i<n;i++) { scanf("%d",&zhong[i]); } for(int i=0;i<n;i++) { scanf("%d",&xian[i]); } Btree *root=build(zhong,xian,n); Reverse(root); CenOrder(root); for(int i=0;i<cur;i++) { if(i==0) printf("%d",ans[i]); else printf(" %d",ans[i]); } printf("\n"); return 0;}
0 0
- 由二叉树中序遍历和先序遍历,构造二叉树,经过镜面翻转后输出层次遍历结果
- 由二叉树的后序和中序求层次遍历
- 由先序遍历和中序遍历构造二叉树的二叉链表代码
- 二叉树的先序遍历,后序遍历,中序遍历,层次遍历
- 二叉树 非递归 先序遍历 中序遍历 后序遍历 层次遍历
- 二叉树-建树,层次遍历,先序遍历,中序遍历,后序遍历
- 根据二叉树中序和后序(先序)遍历结果 重建二叉树
- JS中由先序遍历和中须遍历构造二叉树
- 二叉树3(构造二叉树、先序遍历、中序遍历、后序遍历)
- 通过中序遍历和先序遍历结果构造二叉树
- 先序,中序,后序,层次遍历二叉树
- 由二叉树的前序遍历和后续遍历结果还原二叉树,并后序遍历打印
- 层次遍历二叉树 并输出遍历结果
- 二叉树的后序遍历和层次遍历
- 数据结构之 二叉树的构造与遍历(先序,中序,后序,层次)
- 由先序遍历/后序遍历以及中序遍历重构二叉树
- 代码实现 由二叉树的先序遍历和中序遍历推出后序遍历
- 【二叉树】 根据先序和中序遍历输出后序遍历
- ORA-01033:oracle initialization or shutdown in progress 解决办法
- python复习笔记[8]——I/O及文件处理
- 上传文件
- Ubuntu14.04 安装mongoDB
- [Java] abstract 关键词
- 由二叉树中序遍历和先序遍历,构造二叉树,经过镜面翻转后输出层次遍历结果
- Vim语法检查插件cppSyntaxCheck
- 不借助第三个变量交换两个变量的值
- Divide by Zero 2017 and Codeforces Round #399 (Div. 1 + Div. 2, combined) E
- weboffice 兼容其他 浏览器。
- Python基础入门笔记二...0221
- makefile编写
- webpack react 配置
- 机器学习笔记1:神经网络 反向传播(Backpropagation) week5