資料結構實驗---二叉排序樹的建立
阿新 • • 發佈:2018-12-17
#include<stdio.h> #include<string.h> #include<algorithm> using namespace std; typedef struct node { int key; struct node *l,*r; }bstnode; int bstinsert(bstnode *&p,int k) { if(p==NULL) { p=new bstnode(); p->key=k; p->l=p->r=NULL; return 1; } else if(k==p->key)//去重 return 0; else if(k<p->key) return bstinsert(p->l,k); else return bstinsert(p->r,k); } void build(bstnode *&bt,int *str,int n) { bt=NULL; for(int i=0;i<=n-1;i++) { bstinsert(bt,str[i]);//每次插入都從樹頭開始 } } void preorder(bstnode *bt) { if(bt!=NULL) { printf("%d ",bt->key); preorder(bt->l); preorder(bt->r); } } void inorder(bstnode *bt) { if(bt!=NULL) { inorder(bt->l); printf("%d ",bt->key); inorder(bt->r); } } void posorder(bstnode *bt) { if(bt!=NULL) { posorder(bt->l); posorder(bt->r); printf("%d ",bt->key); } } int main() { int n; int num[10120]; while(~scanf("%d",&n)) { for(int i=0;i<n;i++) { scanf("%d",&num[i]); } bstnode *nd=new bstnode(); build(nd,num,n); preorder(nd); printf("\n"); inorder(nd); printf("\n"); posorder(nd); printf("\n"); } return 0; }