树状搜索功能
任何节点都可以有任意数量的子节点。为了搜索这棵树,我写了这样的东西
function Search(key, nodes){
for (var i = 0; i < nodes.length; i++) {
if (nodes[i].key == key) {
return nodes[i];
}
if (nodes[i].hasOwnProperty('children')) {
return this.Search(key, nodes[i].children);
}
}
,但不太有效......有任何输入吗?
Any node can have any number of children. To search this tree i wrote something like this
function Search(key, nodes){
for (var i = 0; i < nodes.length; i++) {
if (nodes[i].key == key) {
return nodes[i];
}
if (nodes[i].hasOwnProperty('children')) {
return this.Search(key, nodes[i].children);
}
}
which doesn't quite work...any input?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您仅递归搜索具有子节点的第一个节点。
您应该将最后一个条件重写为如下所示:
您还需要添加一个如果未找到节点的情况 - 例如,在函数最底部的
return null
。You only recursively search the first node that has children.
You should rewrite that last conditional to something like this:
You also need to add a case for if the node is not found - for example, a
return null
at the very bottom of the function.您似乎缺少一个基本案例。当您遇到一个没有子节点并且也不是您要查找的节点时会发生什么?
You seem to be missing a base case. What happens when you encounter a node that has no children and also is not the node you're looking for?
如果这是 Javascript,则代码
this.Search
中的this
可能就是给您带来问题的原因。this
表示“当前的 Function 对象”。尝试将this.Search
替换为Search
。If this is Javascript,
this
in your codethis.Search
is probably what's giving you the problem.this
means "the current Function object." Try replacingthis.Search
with justSearch
.