gpt4 book ai didi

C二叉搜索树实现——插入

转载 作者:太空宇宙 更新时间:2023-11-04 04:51:16 26 4
gpt4 key购买 nike

我正在尝试创建一个程序,它将单词列表作为输入,并将它们排序为二叉树,以便能够找到它们,例如像字典。这是我到目前为止所做的,但是 newEl -> el = input; 出现段错误,我知道这是因为它试图指向 NULL el,当树是第一个时创建,但我不确定改进我的代码的最佳方法是什么。有人有主意吗?谢谢。

struct node *tra(struct node * start, Type input) {
struct node * thisNode = start;

if (thisNode == NULL)

Type current = thisNode -> el;

if (strcmp(input, current) > 0)
return tra(thisNode -> right, input);

else if (strcmp(input, current) < 0)
return tra(thisNode -> left, input);

else
return thisNode;
}
}

Ta insert(Type input, Ta ta) {
if ((find(input, ta)) == FALSE) {
newEl -> el = input;

}

return ta;
}

Boolean find(Type input, Ta ta) {
if (tra(ta -> head, input) == NULL)
return FALSE;
}

最佳答案

这是一个指向等效指针的指针:

typedef char *Type;
struct node {
struct node *left , *right;
Type payload;
};

struct node **find_pp(struct node **pp, Type input) {
struct node *thisNode ;

while ( thisNode = *pp ) {
int diff;
diff = strcmp(input, thisNode->payload);
if (!diff) break;
pp = (diff <0) ? &thisNode->left : &thisNode->right;
}
return pp;
}

Boolean find(struct node *root, Type thing)
{
struct node **pp;
pp = find_pp( &root, thing);
return (*pp) ? True : False;
}

void insert (struct node **pp, Type thing)
{
struct node *newNode;
pp = find_pp (pp, thing);

if (*pp) return; /* already exists */
*pp = newNode = malloc (sizeof *newnode);
newNode->payload = strdup(thing);
newNode->left = NULL;
newNode->right = NULL;

return;
}

一些注意事项:

  • 将节点插入到树中意味着:分配给以前为 NULL 的指针
  • 空树也是一棵树:只是一个恰好为空的指针(指向树的根)
  • 在树中找到一个节点意味着:找到应该在的地方(:=指针)(如果它存在的话)
  • 如果它不存在,这个指针就是它应该被插入的地方以使其存在
  • 绘制图表(用纸和铅笔)会有所帮助。

关于C二叉搜索树实现——插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14922802/

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