在任意树C中查找节点
我想使用函数从任意树中查找节点并返回该节点 这是我的结构:在任意树C中查找节点,c,tree,C,Tree,我想使用函数从任意树中查找节点并返回该节点 这是我的结构: typedef struct binary_tree { int index; struct binary_tree * left; struct binary_tree * right; } binary_tree; 我使用的函数是 binary_tree * search (binary_tree * tree, int index) { binary_tree * found = NULL
typedef struct binary_tree {
int index;
struct binary_tree * left;
struct binary_tree * right;
} binary_tree;
我使用的函数是
binary_tree * search (binary_tree * tree, int index) {
binary_tree * found = NULL;
if(tree == NULL)
return NULL;
if(tree->index == index)
return tree;
found = search(tree->left, index);
if (found) {
return found;
}
found = search(tree->right, index);
if (found) {
return found;
}
return NULL;
}
但它不起作用
我需要修改或更正什么才能找到该节点
或者如果你能给我另一个建议,我会很感激的 通常使用键(=yourindex
)对元素进行排序并更快地找到它们
您的代码当前搜索树中的每个元素,即O(n)
,尽管也可以使用O(log n)
正确的解决方案取决于如何在树中存储元素(如何对元素排序)。
下面的示例预期左侧节点索引比右侧节点索引小
binary_tree * search (binary_tree * arbore, int index) {
if(arbore == NULL){
return NULL;
}
if(arbore->index == index){
return arbore;
}
if(arbore->index < index){
return search (arbore->left, index);
}else{
return search (arbore->right, index);
}
}
此外,您应该始终使用括号。省略它们只会导致错误,没有任何好处。你的函数有2个参数,但你用3个参数递归调用它。我修改了函数头,但忘了更改参数,不管怎样,问题不是从那里来的,因为在我的程序中,我已经纠正了参数。是的,我知道你做了什么,但是我的树是任意的,值不是左小右大:),这是我的problem@xyz我不知道如果没有排序,为什么要使用树,但我也更新了我的答案。
binary_tree * search (binary_tree * arbore, int index) {
if(arbore == NULL){
return NULL;
}
if(arbore->index == index){
return arbore;
}
binary_tree* result = NULL;
result = search (arbore->left, index);
if(result == NULL){
result = search (arbore->right, index);
}
return result;
}