[英]Inserting in Binary Search Tree (C) using for loop
我在使用for循环插入二进制搜索树时遇到问题,当我调用InorderTraversal函数时,我得到的所有输出都是空行,据我认为其余的代码还可以,唯一的问题是插入功能。
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
typedef struct BinaryTree{
int data;
struct BinaryTree *left;
struct BinaryTree *right;
} node;
node* Insert(node* head, int value)
{
_Bool flag = true;
for(node *temp = head; flag == true; (temp = (value >= temp->data)?(temp->right):(temp->left)))
{
if(temp == NULL)
{
temp = (node*)malloc(sizeof(node*));
temp->data = value;
temp->left = NULL;
temp->right = NULL;
flag = false;
}
}
return head;
}
void InorderTraversal(node* head)
{
if(head == NULL)
{
return;
}
InorderTraversal(head->left);
printf("%d ",head->data);
InorderTraversal(head->right);
}
int main(void)
{
node *head = NULL;
for(int i = 0; i < 40; i++)
{
head = Insert(head,i);
}
InorderTraversal(head);
return 0;
}
叫我疯了,但是malloc(sizeof(node*))
应该是malloc(sizeof node)
吗?
除了能读懂C语言之外,我还没有那么了解,如果这是错误的话,请原谅...
编辑:...或malloc(sizeof * temp)
当您插入第一个节点时,您在这里取消引用未初始化的指针:
temp->data
其中temp是未初始化的头,并且指向NULL。
因此,当head为NULL时,您首先必须进行特殊情况:
if( !head )
{
head = malloc(sizeof(node));
head->data = value;
head->left = NULL;
head->right = NULL;
return head ;
}
当您继续添加元素时,您不会更新最后一个节点的指针。 您的for循环应具有指向上一个节点的额外指针,当您到达最后一个节点并找到NULL时,请更新前一个节点的左指针或右指针。
if(temp == NULL) //wrong, should be: not equal
{
temp = (node*)malloc(sizeof(node*)); //wrong, should be: sizeof the node not the pointer
temp->data = value;
temp->left = NULL;
temp->right = NULL;
flag = false; //use break instead
}
在此,上一个节点的左或右指针未更新,并且在搜索时找不到任何节点。
在这里尝试在您的插入函数中进行这些更改
node* Insert(node *head, int value)
{
if(!head) //Explicitly insert into head if it is NULL
{
head = malloc(sizeof *head);
head->data = value;
head->left = NULL;
head->right = NULL;
return head;
}
for(node *temp = head,*temp2 = head; ;(temp = (value >= temp->data)?(temp->right):(temp->left)))
{
if(temp == NULL)
{
temp = malloc(sizeof *temp);
temp->data = value;
temp->left = NULL;
temp->right = NULL;
if(value >= temp2->data) //update previous nodes left or right pointer accordingly
temp2->right = temp;
else
temp2->left = temp;
break;
}
temp2 = temp; //Use a another pointer to store previous value of node
}
return head;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.