本帖最后由 jhq999 于 2022-12-13 18:14 编辑 #include <stdio.h>
#include <stdlib.h>
typedef struct _nd
{
int num;
struct _nd *left;
struct _nd *right;
} NODE;
void mbtree(NODE *p1, int num);
int main(void)
{
int data[] = {3, 6, 9, 1, 10, 7};
int i;
NODE *root, *top;
int dsize;
dsize = sizeof(data)/sizeof(int);
for (i = 0; i < dsize; i++)
{
printf("%d ", data[i]);
}
printf("\n");
root = (NODE *) malloc(sizeof(NODE));
if(root == NULL)
{
printf("can not allocate memory\n");
exit(-1);
}
root->num = data[0];
root->left = NULL;
root->right = NULL;
top = root;
printf("root: %d\n", root->num);
for(i = 1; i < dsize; i++)
{
printf("i= %d :", i);
mbtree(top, data[i]);
}
return 0;
}
/* 未完成プログラム */
void mbtree(NODE *p1, int num)
{
/* 値の大小によって左右に振り分ける */
if (p1->num < num) /* 主ノードより大きいとき */
{
/* 右がNULLならそこに新たなノードをぶら下げる */
if (p1->right == NULL)
{
NODE *p2;
p2 = (NODE *)malloc(sizeof(NODE));
if(p2 == NULL)
{
printf("can not allocate memory for mbree\n");
exit(-1);
}
p2->num = num;
p2->left = NULL;
p2->right = NULL;
p1->right = p2;
printf("%d's right is %d\n",p1->num,num);
}
else /* NULLでなければ右側のノードに移動 */
mbtree(p1->right,num);
}
else
{
if (p1->left == NULL)
{
NODE *p2;
p2 = (NODE *)malloc(sizeof(NODE));
if(p2 == NULL)
{
printf("can not allocate memory for mbree\n");
exit(-1);
}
p2->num = num;
p2->left = NULL;
p2->right = NULL;
p1->left = p2;
printf("%d's left is %d\n",p1->num,num);
}
else /* NULLでなければ右側のノードに移動 */
mbtree(p1->left,num);
}
}
3 6 9 1 10 7
root: 3
i= 1 :3's right is 6
i= 2 :6's right is 9
i= 3 :3's left is 1
i= 4 :9's right is 10
i= 5 :9's left is 7
Process returned 0 (0x0) execution time : 0.290 s
Press any key to continue.
|