L2-011. 玩转二叉树
来源:互联网 发布:2017学校网络改造方案 编辑:程序博客网 时间:2024/06/08 06:02
本题要求:
给定一棵二叉树的中序遍历和前序遍历,请你先将树做个镜面反转,再输出反转后的层序遍历的序列。所谓镜面反转,是指将所有非叶结点的左右孩子对换。这里假设键值都是互不相等的正整数。
输入格式:
输入第一行给出一个正整数N(<=30),是二叉树中结点的个数。第二行给出其中序遍历序列。第三行给出其前序遍历序列。数字间以空格分隔。
输出格式:
在一行中输出该树反转后的层序遍历的序列。数字间以1个空格分隔,行首尾不得有多余空格。
输入样例:
71 2 3 4 5 6 74 1 3 2 6 5 7
输出样例:
4 6 1 7 5 3 2
解题思路 :
我也不是很懂为什么调用递归那里的4个参数为什么需要那么写现在就当公式记住啦。left = 中序遍历的开始,根节点在中序的位置 - 1,前序开始 + 1, 根节点在中序的位置 - 中序开始 + 前序开始。right = 根节点在中序的位置 + 1,中序结束,根节点在中序位置 - 中序开始 + 前序开始 + 1,前序结束。希望有懂得大神可以告诉我~
代码 :
#include<iostream>#include<queue>#include<string>#include<cstring>#include<algorithm>using namespace std;class Node { public: int left; int right; Node() { left = -1; right = -1; }};int a[31];//中序int b[31];//前序 Node c[31];int build(int startA, int endA, int startB, int endB) { if (startA > endA || startB > endB) { return -1; } int headB = startB; int headA = endA; while (a[headA] != b[headB]) { headA--; } c[headB].left = build(startA, headA - 1, startB + 1, headA - startA + startB); c[headB].right = build(headA + 1, endA, headA - startA + startB + 1, endB); return headB;}void display(int id) { queue<int> que; que.push(id); int t = -1; while (!que.empty()) { if (t != -1) { cout << " "; } t = que.front(); que.pop(); if (t == -1) { break; } cout << b[t]; if (c[t].right != -1) { que.push(c[t].right); } if (c[t].left != -1) { que.push(c[t].left); } }}int main(){ int n; cin >> n; for (int i = 0; i < n; i++) { cin >> a[i]; } for (int j = 0; j < n; j++) { cin >> b[j]; } int r = build(0, n - 1, 0, n - 1); display(r); 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. 玩转二叉树
- JSON的简单书写(初学),使用Java语言反序列化
- 函数参数默认值设置
- 理解JAVASCRIPT 中hasOwnProperty()的作用
- 阿里云工程师用机器学习破解雾霾成因
- MyBatis学习四 懒加载和缓存
- L2-011. 玩转二叉树
- 数据结构之二叉排序树
- MaxCompute(原ODPS) MapReduce常见问题解答
- hadoop第二天
- RecyclerView中item布局的"match_parent"属性失效--LayoutInflate的深入了解
- Qt之GUI学习笔记(四)——创建对话框
- px与dp与sp之间的转换
- vue组件最佳实践
- JNI交叉编译_NDK插件