输入一个数组, 生成一个二叉树排序树
#include <stdio.h>#include <stdlib.h>
typedef struct node
{
int data;
struct node *lchild, *rchild;
}node, *btree;
btree createNode(int num)
{
btree newnode = (btree)malloc(sizeof(node));
newnode->data = num;
return newnode;
}
void CreateBtreeFromArray(btree *root, int array[] , int begin, int end)
{
if((end - begin)==1){
*root = createNode(array);
}else{
int mid = begin + (end-begin)/2;
*root = createNode(array);
CreateBtreeFromArray(&(*root)->lchild, array, begin, mid);
CreateBtreeFromArray(&(*root)->rchild, array, mid+1, end);
}
}
void in(btree root)
{
if(root)
{
in(root->lchild);
printf("[%d] ",root->data);
in(root->rchild);
}
}
int main(void)
{
int a [] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
int len = sizeof(a)/sizeof(int);
btree root;
CreateBtreeFromArray(&root, a, 0, len);
in(root);
putchar('\n');
return 0;
}
结果总是 segmentation default 这是为什么啊?@人造人 @风扫地 #include <stdio.h>
#include <stdlib.h>
typedef struct node
{
int data;
struct node *lchild, *rchild;
}node, *btree;
btree createNode(int num)
{
btree newnode = (btree)malloc(sizeof(node));
newnode->data = num;
return newnode;
}
void CreateBtreeFromArray(btree *root, int array[], int begin, int end)
{
if((end - begin) == 1)
{
*root = createNode(array);
(*root)->lchild = NULL;
(*root)->rchild = NULL;
}
else
{
int mid = begin + (end - begin) / 2;
*root = createNode(array);
CreateBtreeFromArray(&(*root)->lchild, array, begin, mid);
//CreateBtreeFromArray(&(*root)->rchild, array, mid + 1, end);
CreateBtreeFromArray(&(*root)->rchild, array, mid, end);
}
}
void in(btree root)
{
if(root)
{
in(root->lchild);
printf("[%d] ", root->data);
in(root->rchild);
}
}
int main(void)
{
int a[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
int len = sizeof(a) / sizeof(int);
btree root;
CreateBtreeFromArray(&root, a, 0, len);
in(root);
putchar('\n');
return 0;
}
人造人 发表于 2018-7-16 14:57
后来发现是 少了递归出口
在第28行 加上 if(begin < end) 就好啦 Martine 发表于 2018-7-18 17:08
后来发现是 少了递归出口
在第28行 加上 if(begin < end) 就好啦
嗯
页:
[1]