【发布时间】:2018-09-06 14:39:34
【问题描述】:
struct tnode
{
int val;
struct tnode *left;
struct tnode *right;
};
int search(struct tnode *root, int val)
{
int p = 0;
int q = 0;
if (!root) return 0;
p = search(root->left, val);
if (p == 1) return 1;
if (root->val == val) return 1;
q = search(root->right, val);
if (q == 1) return 1;
}
当搜索树时找不到val 时,我不明白上述代码如何返回0。
【问题讨论】:
-
将最后两行替换为
return q; -
获取tour、阅读How to Ask和minimal reproducible example。没有 MCVE,很难确定问题出在哪里。
-
是的,这有效,但我想知道为什么上面的代码有效。因为,在某个时间点没有返回值。当 root 变为 null 时,它向被调用函数返回 0 并存储在 p 或 q 中,但它们都不会再次返回。
-
为什么还要有这样的功能?通常,树搜索函数返回节点或指向它的指针。只要知道它就在那里,您仍然必须搜索它才能对它做任何事情。你所拥有的,是无用的练习。
标签: c search data-structures binary-tree