首先,要明白二叉搜索树前序序列可以唯一确定一棵二叉搜索树。
第一步,建立根节点(序列的第一个值)
第二步,获得右子树第一个结点的偏移k(用来划分区间)
第三步,划分左右子树的区间
#include<iostream>
#include<vector>
using namespace std;
typedef struct Node* Tree;
const int N = 1010;
vector<int> hx,qx,zx;
int a[N];
struct Node{
int data;
Tree l,r;
Node(int _data){
data = _data;
l = r = nullptr;
}
};
// l为序列的开始部分,sz为序列的大小
void build(int l,int sz,Tree &tree){
if(sz <= 0) return;
tree = new Node(a[l]);
int k = 1;
while(l+k < sz && a[l+k] < a[l]) k++;
qx.push_back(tree->data);
build(l+1,k-1,tree->l);
zx.push_back(tree->data);
build(l+k,sz-k,tree->r);
hx.push_back(tree->data);
}
int main(){
int n;
cin>>n;
for(int i = 0; i < n; i++) cin>>a[i];
Tree root = nullptr;
build(0,n,root);
cout<<"先序遍历:";
for(auto num:qx) cout<<num<<' ';
cout<<"\n中序遍历:";
for(auto num:zx) cout<<num<<' ';
cout<<"\n后序遍历:";
for(auto num:hx) cout<<num<<' ';
return 0;
}
/*
7
8 6 5 7 10 8 11
*/