gpt4 book ai didi

c - 使用 for 循环插入二叉搜索树 (C)

转载 作者:行者123 更新时间:2023-11-30 17:40:11 25 4
gpt4 key购买 nike

我在使用 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;
}

最佳答案

在这里尝试在插入函数中进行这些更改

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;
}

关于c - 使用 for 循环插入二叉搜索树 (C),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21590406/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com