标题:
用C语言这么构建一个二叉树不成功原因?想求助一下
[打印本页]
作者:
chao超
时间:
2018-8-11 13:55
标题:
用C语言这么构建一个二叉树不成功原因?想求助一下
typedef struct node Binary_Tree;
typedef struct node
{
int data;
struct node *leftnode;
struct node *rightnode;
}Binary_Tree,*Tree;
u8 Make_BinaryTree( Binary_Tree *tree , int *p )
{
static int *q; q=p;
if( *q==0)
{
tree=NULL;
q++;
return 0;
}
else
{
tree=(Binary_Tree *)malloc(sizeof(Binary_Tree));
tree->data=*q;
printf("%d \n", tree->data);
q++;
Make_BinaryTree( tree->leftnode , q );
Make_BinaryTree( tree->rightnode ,q );
}
return 0;
}
void Initialization_BinaryTree(void)
{
int array[]={1,2,3,0,0,4,0,0,5,6,0,0,7,0,0 };
Binary_Tree tree;
Make_BinaryTree( &tree , &array[0] );
printf("%d \n" ,tree.data);
printf("%d \n" ,tree .rightnode->data);
printf("%d \n" ,tree.leftnode->data);
这三个输出都是乱码,我不知道二叉树的建立过程中问题在哪里,我应该在每个节点都分配了内存,不过结果好像有问题
}
作者:
angmall
时间:
2018-8-11 17:23
给你一个试试
/*-------------------------------------------------*/
#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
int val;
struct node * left;
struct node * right;
} node_t;
void insert(node_t * tree,int val);
void print_tree(node_t * current);
void printDFS(node_t * current);
int main()
{
node_t * test_list = malloc(sizeof(node_t));
/* set values explicitly, alternative would be calloc() */
test_list->val = 0;
test_list->left = NULL;
test_list->right = NULL;
insert(test_list,5);
insert(test_list,8);
insert(test_list,4);
insert(test_list,3);
printDFS(test_list);
printf("\n");
}
void insert(node_t * tree, int val)
{
if (tree->val == 0)
{
/* insert on current (empty) position */
tree->val=val;
}
else
{
if (val < tree->val)
{
/* insert left */
if (tree->left != NULL)
{
insert(tree->left, val);
}
else
{
tree->left = malloc(sizeof(node_t));
/* set values explicitly, alternative would be calloc() */
tree->left->val = val;
tree->left->left = NULL;
tree->left->right = NULL;
}
}
else
{
if (val >= tree->val)
{
/* insert right */
if (tree->right != NULL)
{
insert(tree->right,val);
}
else
{
tree->right=malloc(sizeof(node_t));
/* set values explicitly, alternative would be calloc() */
tree->right->val=val;
tree->right->left = NULL;
tree->right->right = NULL;
}
}
}
}
}
/* depth-first search */
void printDFS(node_t * current)
{
/* change the code here */
if (current == NULL) return; /* security measure */
if (current->left != NULL) printDFS(current->left);
if (current != NULL) printf("%d ", current->val);
if (current->right != NULL) printDFS(current->right);
}
复制代码
作者:
chao超
时间:
2018-8-11 20:37
很感谢给代码,我主要是问问这么写到底错在哪里,我知道别的写法可以只是这种为什么不行
作者:
angmall
时间:
2018-8-11 23:05
再好好看看书,看看别人的程序吧。
作者:
zhaoyinlo
时间:
2018-9-3 12:44
再看看二叉树的知识点吧 看看它的基本操作
欢迎光临 (http://www.51hei.com/bbs/)
Powered by Discuz! X3.1