以下のプログラムはツリーを考えるものです。
#include<stdio.h>
#include<stdlib.h>
/*構造体を宣言する*/
struct node
{
int data;
struct node *left;
struct node *right;
};
void print_tree(struct node *p);
int main(void)
{
/*変数宣言*/
struct node *root,*tmp,*p;
int d,flg;
/*ツリーを初期化する*/
root = NULL;
/*最初のデータを入力する*/
printf("Input Number : ");
scanf("%d",&d);
while(d > 0)
{
/*要素を作成する*/
tmp = malloc(sizeof(struct node));
tmp->data = d;
tmp->left = NULL;
tmp->right = NULL;
if(root == NULL)
{
/*ルートにくっつける*/
root = tmp;
}
else
{
p=root;
flg = 0;
while(flg == 0)
{
if(tmp->data < p->data)
{
if(p->left == NULL)
{
/* 左にくっつける*/
printf("%dの左につけた\n",p->data);
p->left = tmp;
flg = 1;
}
else
{
p = p->left;
}
}
else
{
if(p->right == NULL)
{
printf("%dの右につけた\n",p->data);
p->right = tmp;
flg =1;
}
else
{
p = p->right;
}
}
}
}
/*次のデータを入力する*/
printf("Input Number : ");
scanf("%d", &d);
}
/*画面に出力する*/
printf("Result : ");
print_tree(root);
printf("\n");
return 0;
}
/*ツリーを出力する関数*/
void print_tree(struct node *p)
{
if(p != NULL)
{
/*自分自身を出力する*/
printf("%d",p->data);
/*左側を出力する*/
print_tree(p->left);
/*右側を出力する*/
print_tree(p->right);
}
}
これを行きがけ順にしたいです。よろしくお願いします。