树搜索功能

sar*_*ake 0 tree-structure tree-search

任何节点都可以包含任意数量的子节点.为了搜索这棵树我写了这样的东西

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);
        }


    }
Run Code Online (Sandbox Code Playgroud)

哪个不太有效...任何输入?

Ano*_*on. 5

您只能递归搜索具有子节点的第一个节点.

您应该将最后一个条件重写为以下内容:

if (nodes[i].hasOwnProperty('children')) {
    var node = this.Search(key, nodes[i].children);
    if(node != null)
        return node;
}
Run Code Online (Sandbox Code Playgroud)

如果找不到节点,您还需要添加一个案例 - 例如,return null在函数的最底部.