C二进制搜索树实现

编程入门 行业动态 更新时间:2024-10-24 18:17:07
本文介绍了C二进制搜索树实现-插入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

I am trying to create a program which which takes a list of words as an input, and sorts them into a binary tree, in order to allow them to be found, e.g. like a dictionary. This is what I have done so far, but am getting a segmentation error with newEl -> el = input; I know this is because it is trying to point to a NULL el, when the tree is first created, but i'm not sure what the best way to improve my code would be. Anyone have any ideas? Thanks.

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

推荐答案

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

This is a pointer to pointer equivalent:

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

一些注意事项:

a few notes:

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

更多推荐

C二进制搜索树实现

本文发布于:2023-11-29 08:21:39,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1645851.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!