您正在覆盖节点参数变量:
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!
你不应该!
将参数定义为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); }
当字符串不在leftsubtree中时,递归搜索返回NULL,您指定它 node 。然后 search_RtLR(node->right, str) 搜索'无处'。你不应该覆盖你的 node :
node
search_RtLR(node->right, str)
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;