简体   繁体   English

在C中的二叉树中递归搜索

[英]Search recursively in binary tree in C

The function receives parameter node (has member name) and str (the name to search) 该函数接收参数节点(具有成员名称)和str(要搜索的名称)

{
    if (node == NULL) return NULL;
    if (strcmp(node->name, str) == 0) return node;
    node = search_RtLR(node->left, str);
    if (node != NULL) return node;
    node = search_RtLR(node->right, str);
    if (node != NULL) return node;

    return NULL;
}

When I search a name that is in left subtree, it works, but when I search in right subtree the program terminates(also when there is no such name in the tree), and I can't find what's wrong. 当我搜索在左子树中的名称时,它可以工作,但是当我在右子树中搜索时,程序终止(同样,当树中没有这样的名称时),我找不到问题所在。 The tree is not sorted in alphabetical order. 该树未按字母顺序排序。

You're overwriting your node parameter variable: 您正在覆盖节点参数变量:

node = search_RtLR(node->left, str); // overwriting node here at assignment
if (node != NULL) return node;
node = search_RtLR(node->right, str); // node is NULL here, look at line above!

You shouldn't! 你不应该!

Defining your parameters as const (since this is a function that does not change any data) also helps (as the compiler will warn you if you try to overwrite the const variables): 将参数定义为const(因为此函数不会更改任何数据)也有帮助(因为如果您尝试覆盖const变量,编译器会警告您):

Node* search_RtLR(const Node* node, const char* str) {
    if (node == NULL) return NULL;
    if (strcmp(node->name, str) == 0) return node; 
    const Node* newNode = search_RtLR(node->left, str);
    if (newNode != NULL) return newNode;
    return search_RtLR(node->right, str);
}

When the string is not in the leftsubtree the recursive search returns NULL, which you assign to node . 当字符串不在leftsubtree中时,递归搜索返回NULL,您将其分配给node Then search_RtLR(node->right, str) searches 'nowhere'. 然后search_RtLR(node->right, str)搜索“无处”。 You should not overwrite your node : 您不应该覆盖您的node

if (node == NULL) return NULL;
if (strcmp(node->name, str) == 0) return node;
node1 = search_RtLR(node->left, str);
if (node1 != NULL) return node1;
node1 = search_RtLR(node->right, str);
if (node1 != NULL) return node1;

return NULL;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM