二叉排序樹的建立與中序遍歷
阿新 • • 發佈:2019-02-08
編譯器:Xcode
程式語言:C
data1.txt文字資料為上圖,在我的電腦裡它的儲存位置是:/Users/wsw/Desktop/資料結構/data1.txt
#include<stdio.h>
#include<stdlib.h>
#define N 100
typedef struct node //二叉排序樹結點定義
{
int key; //結點值
struct node *lchild,*rchild; //左、右孩子指標
}bsnode;
typedef bsnode *bstree;
//從檔案中讀入資料存入陣列a
int readData(int a[], int n,char *f ) //函式返回成功讀入放入資料個數
{
FILE *fp;
int i;
fp=fopen(f,"r");
if (fp==NULL) return 0;
else
{
for (i=0; i<n && !feof(fp); i++)
fscanf(fp,"%d",&a[i]);
fclose(fp);
return i;
}
}
void output(int a[],int n) //輸出陣列的內容
{
int i;
printf("陣列的內容是:");
for (i=0; i<n; i++)
{
if (i%10==0)
printf("\n");
printf("%7d",a[i]);
}
printf("\n");
}
bstree creatBstree(int a[],int n) //非遞迴建立二叉排序樹
{
//根據輸入的結點序列,建立一棵二叉排序樹,並返回根結點的地址
bstree bt;
bt=(bstree)malloc(sizeof (bsnode));
bt->key=a[0];
bt->lchild=bt->rchild=NULL;
for(int i=1;i<n;i++)
{
bstree s,p=bt,q;
s=(bstree)malloc(sizeof(bsnode));
s->key=a[i];
s->lchild=s->rchild=NULL;
while (p)
{
if (p->key>a[i])
{
q=p;
p=p->lchild;
}
else
{
q=p;
p=p->rchild;
}
}
if (q->key>a[i])
q->lchild=s;
else
q->rchild=s;
}
return bt;
}
/*
p是待判斷的節點,一個要插入的節點需要和p節點的值進行比較,
比p的值大,就往p的右孩子找,p=p->rchild,
比p的值小,就往p的左孩子找,p=p->lchild;
q記錄的是當前需要插入節點的父親節點,
當前需要插入節點的值比它的值小,成為它的左孩子,q->lchild=s,
當前需要插入節點的值比它的值大,成為它的右孩子,q->rchild=s
*/
void inorder(bstree t) //中序遍歷二叉排序樹
{
if (t)
{
inorder(t->lchild);
printf("%8d",t->key);
inorder(t->rchild);
}
}
//中序遍歷的原因是:對於二叉排序樹,中序遍歷的結果就是從小到大排列的,所以可以用來判斷二叉排序樹是否成功建立.
int main()
{
int n,a[N];
bstree t;
n=readData(a,N,"/Users/wsw/Desktop/資料結構/data1.txt");
output(a,n);
t=creatBstree(a,n); //建立二叉排序樹
printf("中序遍歷:\n");
inorder(t);
return 0;
}
執行結果: