//算法思想:根據輸入序列建立二叉排序樹,最後用後序遍歷輸出該二叉樹
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define N 100
struct Node{
struct Node *lchild;
struct Node *rchild;
int c;
}Tree[N];//靜態結點N個
int loc=0;
Node *create(){//靜態分配一個結點
Tree[loc].lchild=Tree[loc].rchild=NULL;
return &Tree[loc++];
}
int count=0;//輸入整數數組的下標
Node * bstInsert(Node *T,int key){//二叉排序樹的創建,其一定是插在根節點上的
if(T==NULL){T=create();T->c=key;return T;}
if(key<T->c){T->lchild=bstInsert(T->lchild,key);}
if(key>T->c){T->rchild=bstInsert(T->rchild,key);}
return T;//返回根節點指針
}
void postOrder(Node *T){//後序遍歷輸出字符串
if(T->lchild!=NULL)postOrder(T->lchild);
if(T->rchild!=NULL)postOrder(T->rchild);
printf("%d ",T->c);
}
int main(){
int temp[N];
int i=0;
scanf("%d",&temp[i]);
while(temp[i]!=0){
scanf("%d",&temp[++i]);
}//輸入數據
Node *T=NULL;
int count=0;
while(temp[count]!=0){
T=bstInsert(T,temp[count++]);
}
postOrder(T);
printf("\n");
return 0;
}
USTC機試—根據文件中的一串數字建立二叉排序樹並且
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.