【发布时间】:2021-07-12 03:18:15
【问题描述】:
我有一棵像这样的二叉树(不是二叉搜索树,BST)
// node in a tree
typedef struct
{
int id; // node index in a tree
int value; // data on node
struct Node* l; // left child
struct Node* r; // right child
} Node;
// a tree with only its root node
typedef struct
{
Node* root;
} BiTree;
我想通过其id(对于给定索引idToBeFound)找到一个节点并返回找到的节点的指针。
我的搜索功能findNode 适用于下面的case 1,但不适用于case 2(似乎进入了无限循环):
示例(此处显示的数字是节点的索引和value=id 为简单起见):如果查找 id = 2 的节点,则输出应该是节点 2 的指针。
case 1:
1
/ \
2
/ \
3
/ \
case 2:
1
/ \
2
/ \
3
/ \
// finds a node in a tree and returns its pointer
Node* findNode(Node *node, int idToBeFound)
{
printf("traversing node %.2d with value = %d\n", node->id, node->value);
if (node == NULL)
{
printf("Failed to find!");
return NULL;
}
if (idToBeFound == node->id)
{
printf("returning node %d\n", node->id);
return node;
}
Node* node1 = findNode(node->l, idToBeFound);
if(node1 != NULL)
{
printf("returning the left child of node %d\n", node->id);
return node1;
}
Node* node2 = findNode(node->r, idToBeFound);
if(node2 != NULL)
{
printf("returning the right child of node %d\n", node->id);
return node2;
}
}
int main(void)
{
BiTree tree;
initTree(&tree);
//tree.root = (Node*) malloc(sizeof(Node));
//createTreePreOderRecur(tree.root); // create a tree recursively
printf("Demo: find a node via its id in a tree:\n");
int IdToBeFound = 2;
printf("Id of node to be found = %d\n", IdToBeFound);
Node* nodeFound = (Node*) malloc(sizeof(Node));
nodeFound = findNode(tree.root, IdToBeFound);
printf("the found node is: id = %d, value = %d\n", nodeFound->id, nodeFound->value);
//destoryTreeRecur(tree.root);
return 0;
}
函数findNode有什么问题吗? (其他代码运行良好,此处忽略)。谢谢。
【问题讨论】:
-
如果
node1和node2都是NULL会发生什么?看起来函数findNode()最后缺少return NULL。你的编译器应该已经警告你了。如果没有,请打开编译器警告并修复所有警告。 -
Node* nodeFound = (Node*) malloc(sizeof(Node)); nodeFound = findNode(tree.root, IdToBeFound); -
@wildplasser:我释放了
nodeFound,但问题仍然存在,所以可能不是由于内存泄漏。 -
@G。 Sliepen:我在
if(node2 != NULL){...}后面加了一行代码return NULL;,用于你指出的情况,不起作用。 -
会不会是创建树的函数有bug?
标签: c search binary-tree