已知先序序列(preorder)和中序序列(inorder),构造出的二叉树是唯一的。
已知后序序列(postorder)和中序序列(inorder),构造出的二叉树是唯一的。
先序、中序序列构造二叉树,然后先序遍历:
#include <cstdio>
#include <vector>
using namespace std;
//声明结点
struct node
{
int val;
node *left;
node *right;
};
//先序序列
vector<int> pre;
//中序序列
vector<int> in;
int n;
bool flag=false;
//构造二叉树
node *build(int preindex,int instart,int inend)
{
node *root=NULL;
int i;
int mid=-1;
for(i=instart;i<=inend;i++)
{
if(pre[preindex]==in[i])
{
mid=i;
break;
}
}
if(mid!=-1)
{
root=new node;
root->val=pre[preindex];
root->left=build(preindex+1,instart,mid-1);
root->right=build(preindex+mid-instart+1,mid+1,in