输入节点个数
后两行分别输入层次遍历序列、中序遍历序列
使用build()函数建立二叉树,先找到根节点,再划分左右子树,分别构建两棵子树。
并将左右节点分别保存至lch、rch数组中,且保存的是其下标(无左节点时,lch=0;无右孩子时,rch=0)
第一个根节点时根节点的第一个节点,
之后子树的根节点寻找办法是,根据已经划分左右子树在中序遍历的序列中,找到第一个在层序遍历中找到的结点,则为子树的根节点。
具体代码见下面:
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <iostream>
#include <algorithm>
using namespace std;
typedef long long ll;
//还原二叉树
//输入二叉树的层次遍历序列和中序遍历序列
//求这棵二叉树的先序遍历序列和后序遍历序列
// N 代表二叉树的节点个数
/*
7
3 5 4 2 6 7 1
2 5 3 6 4 7 1
*/
const int maxn =30+5;
int inOrder[maxn];//中序遍历序列
int leverOrder[maxn];//层序遍历序列
int preOrder[maxn];//先序遍历序列
int postOrder[maxn];//后序遍历序列
int lch[maxn];
int rch[maxn];
int N; //结点个数
int find(int l, int r){
for(int i=1;i<=N;i++){
for(int j=l;j<=r