#include<bits/stdc++.h>
using namespace std;
int n,a[105];
typedef struct BtNode
{
BtNode *leftchild;
BtNode *rightchild;
int val;
}BtNode,*Btree;
Btree newNode(int v){
BtNode *node = new BtNode;
node->val = v;
node->leftchild = NULL;
node->rightchild = NULL;
return node;
}
void Bst(BtNode *&root,int a[],int st,int ed){
if(st > ed) {root = NULL;return ;}
if(root == NULL){
root = newNode(a[st]);
}
int i = st + 1,temp = root->val;
while(i <= ed && a[i] < temp) i++;//找到一个大于temp值的位置
Bst(root->leftchild,a,st + 1,i - 1);
Bst(root->rightchild,a,i,ed);
}
void postorder(Btree t){
if(t != NULL){
postorder(t->leftchild);
postorder(t->rightchild);
printf("%d ",t->val);
}
}
int main(){
BtNode *root = NULL;
scanf("%d",&n);
for(int i = 0; i < n; i++) scanf("%d",&a[i]);
Bst(root,a,0,n-1);
postorder(root);
return 0;
}
已知二叉排序树的先序求后序
最新推荐文章于 2022-05-22 14:33:31 发布