我正在使用三元搜索树。下面的代码应该可以让您大致了解树的外观。每个叶子都包含一个指向链表的指针,该链表包含指向头节点的指针。每个叶子最多可以有 3 个节点。因此,在根叶填充了 3 个数据值后,下一个值如果小于第一个节点,将插入到左侧;如果大于,则插入到右侧;如果它位于中间,则将插入到右侧。插入中间的 child 。
struct data
{
int val;
};
struct node
{
struct node* next;
struct data* dta;
};
struct linkedList
{
int size;
struct node *head;
};
struct leaf
{
struct linkedList* ll;
struct leaf* left;
struct leaf* right;
struct leaf* center;
struct leaf* parent;
};
struct tree
{
struct leaf* root;
};
我目前正在尝试创建一个函数,该函数接受树和 int 值作为输入。然后它检查树中的每个叶子,看看某个叶子是否等于 int 值,如果等于,则返回 1,否则返回 0。
以下是我的代码
int totalLeaf(struct leaf *lf)
{
int sum = 0;
struct node *temp = lf->ll->head;
while(temp!=NULL)
{
sum = sum + temp->dta->val;
temp = temp->next;
}
printf("sum is : %d\n",sum);
return sum;
}
int searchTotal(struct tree *tr,int total)
{
if(tr->root == NULL)
{
return 0;
}
else
{
return searchTotal_r(tr->root,total);
}
}
int searchTotal_r(struct leaf *lf,int total)
{
if(lf==NULL)
{
return 0;
}
if(totalLeaf(lf) == total)
{
return 1;
}
else
{
searchTotal_r(lf->left,total);
searchTotal_r(lf->center,total);
searchTotal_r(lf->right,total);
}
return 0;
}
有人可以建议我哪里出了问题以及如何解决这个问题吗?
最佳答案
else
{
searchTotal_r(lf->left,total);
searchTotal_r(lf->center,total);
searchTotal_r(lf->right,total);
}
更改为:
else
{
return searchTotal_r(lf->left,total) ||
searchTotal_r(lf->center,total) ||
searchTotal_r(lf->right,total);
}
按照您目前的方式,递归搜索实际上并不重要,因为即使您找到了某些内容,您也总是返回 0。
关于c - 树的搜索功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27160804/