gpt4 book ai didi

c - 我无法将节点插入二叉搜索树

转载 作者:太空宇宙 更新时间:2023-11-04 08:55:01 24 4
gpt4 key购买 nike

我想写一个BST,但是插入函数不起作用。调试了一下,发现没有插入。

/* Binary Search Tree (BST).demo */
#include <stdio.h>
#include <stdlib.h>

typedef struct treeNode{
int data;
struct treeNode* lChild;
struct treeNode* rChild;
} treeNode;

treeNode* createNode(){
treeNode *nNode;
nNode=(struct treeNode*)malloc(sizeof(treeNode));
nNode->data=0;
nNode->lChild=NULL;
nNode->rChild=NULL;

return nNode;
}

void insert(treeNode* rt,int idata)
{
if(rt==NULL){
treeNode* nNode;
nNode=createNode();
nNode->data=idata;
rt=nNode;
rt->lChild=NULL;
rt->rChild=NULL;
}else{
if(idata < rt->data)
insert(rt->lChild,idata);
else insert(rt->rChild,idata);

}
}

int main()
{
treeNode *root;
root=(treeNode*)malloc(sizeof(treeNode));
root->data=15;
root->lChild=NULL;
root->rChild=NULL;

insert(root,13);
if(root->lChild==NULL)
printf("root no l child\n");
// printf("root lchild data :%d",root->lChild->data);
return 0;
}

最佳答案

将其用作插入函数:

void insert(treeNode** rt,int idata)
{
if((*rt)==NULL)
{
treeNode* nNode;
nNode=createNode();
nNode->data=idata;
*rt=nNode;
(*rt)->lChild=NULL;
(*rt)->rChild=NULL;
}
else
{
if(idata < (*rt)->data)
insert(&((*rt)->lChild),idata);
else
insert(&((*rt)->rChild),idata);
}
}

main() 中的插入函数调用如下:

insert(&root,13);

关于c - 我无法将节点插入二叉搜索树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17638926/

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