Suppose that all the keys in a binary tree are distinct positive integers. Given the postorder and inorder traversal sequences, you are supposed to output the level order traversal sequence of the corresponding binary tree.
Input Specification:
Each input file contains one test case. For each case, the first line gives a positive integer N (<=30), the total number of nodes in the binary tree. The second line gives the postorder sequence and the third line gives the inorder sequence. All the numbers in a line are separated by a space.
Output Specification:
For each test case, print in one line the level order traversal sequence of the corresponding binary tree. All the numbers in a line must be separated by exactly one space, and there must be no extra space at the end of the line.
Sample Input:
7
2 3 1 5 7 6 4
1 2 3 4 5 6 7
Sample Output:
4 1 6 3 5 7 2
题目大意:给定一棵二叉树的后序遍历和中序遍历,请你输出其层序遍历的序列。这里假设键值都是互不相等的正整数
分析:与后序中序转换为前序的代码相仿(无须构造二叉树再进行广度优先搜索~),只不过加一个变量index,表示当前的根结点在二叉树中所对应的下标(从0开始),所以进行一次输出先序的递归过程中,就可以把根结点下标index及所对应的值存储在map<int, int> level中,map是有序的会根据index从小到大自动排序,这样递归完成后level中的值就是层序遍历的顺序~~
如果你不知道如何将后序和中序转换为先序,请看-> https://www.liuchuo.net/archives/2090
#include
#include
#include
————————————————
版权声明:本文为优快云博主「柳婼」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.youkuaiyun.com/liuchuo/article/details/52137796
注:只知道前序后序不一定能确定唯一的二叉树,因为只能确定父子节点而无法确定左右子树。
前序中序转后序
算法描述
1在前序序列中找到根节点
2在中序序列中查找这个根节点,确定左右子树。
3对左右子树递归进行步骤1,2。
4输出根节点
递归实现
#include
#include
using namespace std;
string pre, in;
void creatTree(int s, int e, int rootindex) {//s,e,中序的子树范围,前序中的根节点下标
if (s <=e) {//递归出口s>e
int index = s;
while (in[index] != pre[rootindex]) { index++; }//在中序中查找根节点。
creatTree(s, index - 1, rootindex + 1);//左子树
creatTree(index + 1, e, rootindex + 1 + (index - s));//右子树
cout << in[index];//根节点
}
}
int main() {
cin >> pre >> in;
creatTree(0, in.size() - 1, 0);
return 0;
}
/数据前序中序
ACDEFHGB
DECAHFBG
结果
EDCHBGFA/
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
后序中序转前序
算法描述
1在后序序列中找到根节点
2在中序序列中找到该根节点的位置,确定左右子树范围
3输出根节点
3对左右子树递归重复步骤1,2,3。
递归代码
#include
#include
using namespace std;
string post, in;
void creatTree(int s, int e, int rootindex) {//s,e,中序的子树范围,后序中的根节点下标
if (s <=e) {//递归出口s>e
int index = s;
while (in[index] != post[rootindex]) { index++; }//在中序中查找根节点。
cout << in[index];//根节点
creatTree(s, index - 1, rootindex -1-(e-index));//左子树
creatTree(index + 1, e, rootindex -1);//右子树
}
}
int main() {
cin >> in >> post;
creatTree(0, in.size() - 1, post.size() - 1);
return 0;
}
/*数据中序后序
ADEFGHMZ
AEFDHZMG
输出
GDAFEMHZ
*/
————————————————
版权声明:本文为优快云博主「簇僵僵」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.youkuaiyun.com/pilipilipan/article/details/79875101
今天学习了递归,便来这总结一下,因为二叉树还有汉诺塔问题都是递归问题的非常典型的例子,所以借着讲讲。
上面两个大佬把代码整理的很详细了,说到递归,就是大问题和小问题都是一样的求解思路,把小问题解决了大问题回溯到大问题上来,也就能解决大问题了。
我们平时处理问题:可大致分为两种:线性问题和非线性问题。面对递归过程:线性问题就是如阶乘,大问题和小问题之间是线性的。而汉诺塔问题和二叉树都不是线性相关的,我们这时候就要用到计算思维来面对这两个事情,用计算机的思维思考这件事情,函数内部处理的是我们不需考虑的!
结合这个思想再看上边的具体应用,还有dfs等应用,思路是不是清晰了很多。