我有一个以 id 为键的 BST,如下所示:
struct node
{
int id;
char name[100];
struct node *right;
struct node *left;
};
这是搜索ID的代码:
struct node* search(struct node *root, int x)
{
if(root==NULL || root->id==x)
return root;
else if(x>root->id)
return search(root->right, x);
else
return search(root->left,x);
}
但是如果我想搜索一个名字呢?是否可以?有什么建议吗?谢谢
由于二叉树是根据键排序的,因此int id
您需要遍历树的所有节点以使用字符串函数找到具有指定名称的节点strcmp
。
例如
#include <string.h>
//...
struct node* search(struct node *root, const char *name )
{
if(root==NULL || strcmp( root->name, name ) == 0 )
{
return root;
}
else
{
struct node *target = search(root->left, name);
return target != NULL ? target : search(root->right, name);
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句