« 回覆文章 #1 於: 八月 24, 2015, 02:19:19 am »
#include <stdio.h> //標準輸出入函數的標頭檔
#include <stdlib.h>
typedef struct node//節點結構的自定型別定義
{
int data;//整數
struct node *left;//節點的指標
struct node *right;//節點的指標
} Node;
Node* NewNode()
{
Node *newNode = malloc(sizeof(Node));//新節點(node)
newNode->data = 0;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}
void Travel(Node* curNode)
{
if (curNode==NULL)
return;
Travel(curNode->left);//走訪左子樹
printf("%3d ", curNode->data);//走訪樹根
Travel(curNode->right);//走訪右子樹
}
int main(int argc, char *argv[])//
{//程式寫在main()函數裡
Node* Tree = NewNode();
Node* curNode = NULL;
int i, newdata;
srand( (unsigned) time( NULL ) );//srand()是產生亂數的種子
//插入20個資料項到這個樹
newdata = rand()%100;
Tree->data = newdata;
for (i=1; i< 20; i++)
{
newdata = rand()%100;
curNode = Tree
while (1)
{
if (newdata < curNode->data)
{
if (curNode->left == NULL)
{
curNode->left = NewNode();
curNode->left->data = newdata;
break;
}
else
curNode = curNode->left;
}
else
{
if (curNode->right == NULL)
{
curNode->right = NewNode();
curNode->right->data = newdata;
break;
}
else
curNode = curNode->right;
}
}
}
//使用中序列印出整個二元搜尋樹
Travel(Tree);
return 0;
}