【发布时间】:2014-03-01 21:14:49
【问题描述】:
我正在尝试创建一棵二叉树,并且我是数据结构的新手。 我要做的是:
(1) 在终端取树的大小(节点总数)。
(2) 然后在终端从用户处读取最大大小的节点
(3) 然后创建二叉搜索树。
注意:我必须在函数调用中仅通过引用传递节点(没有其他选项)。
它编译没有错误,但我想有任何逻辑问题。当我尝试在 for 循环中插入第二个节点时出现分段错误(首先它工作正常)但编译没有错误。我我无法预测这是由于哪一行代码? 当我这样做时:
How many nodes are to be inserted ?
5
enter the nodes
1 //I am not able to add more nodes
Segmentation fault (core dumped)
欢迎使用任何语言 c/c++ 甚至算法回答。
我这样做的代码是:
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <string.h>
struct node
{
int freq;
struct node * left, * right;
};
typedef struct node node;
/////////////////////////////////////////////////////////////Function definitions //////////////////////////////////////////////////
insert_first_node(int data, node * * Node)
{
node * temp1 ;
temp1 = Node;
temp1= (node * ) malloc(sizeof(node));
temp1 -> freq = data;
temp1 -> left = NULL;
temp1 -> right = NULL;
}
////////////////////////////////////////////////////////////////////
insert_beginning(int data, node * * Node)
{
root = * Node;
root = (node * ) malloc(sizeof(node));;
if (root ==NULL)
{
insert_first_node(data, & root);
}
if (data <= root -> freq)
{
insert_beginning(data, & root -> left);
} else
{
insert_beginning(data, & root -> right);
}
*Node = root;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
main()
{
int i, size, data;
node * head;
head = NULL;
printf("How many nodes are to be inserted ?\n");
scanf("%d", & size);
for (i = 1; i <= size; i++)
{
printf("enter the nodes \n");
scanf("%d", & data);
insert_beginning(data, & head);
}
}
【问题讨论】:
标签: c data-structures tree binary-tree