都知道,树的先根遍历和后根遍历分别对应了二叉树的先序遍历和中序遍历,而由先序遍历和中序遍历可以确定唯一的二叉树。
#include<iostream>
#include<bits/stdc++.h>
#include<vector>
using namespace std;
vector<int>pre;//保存先序遍历结果
vector<int>post;//保存后序遍历结果
int bitree[100];//保存二叉树列表形式结果
int n;
int first_son(int t,int * pa){
// 得到树的第一个孩子
for (int i = 0;i<n;i++){
if(pa[i] == t)return i;
}
return -2;
}
int next_sib(int t,int * pa){
// 得到树的孩子的下一个兄弟
for(int i = t+1;i<n;i++){
if(pa[i] == pa[t])return i;
}
return -2;
}
void pre_root(int t,int *pa){
// 先根遍历
pre.push_back(t);
for(int x = first_son(t,pa);x!=-2;x = next_sib(x,pa)){
pre_root(x,pa);
}
}
void post_root(int t,int * pa){
// 后根遍历
for(int x = first_son(t,pa);x!=-2;x = next_sib(x,pa)){