Node.js 转:Dijkstra 是对的,递归不应该困难

chenge · 2017年08月08日 · 最后由 zzz6519003 回复于 2019年12月11日 · 6449 次阅读

这篇写递归的感觉还不错的。

tree 的例子也很清楚,json 描述很简明。

let tree = {
    name: 'A',
    value: 4,
    children: [
        {
            name: 'B', value: 7,
            children: [{name: 'C', value: 9, children: []}]
        },
        {
            name: 'D', value: 11,
            children: [{name: 'E', value: 9, children: []}]
        },
        {name: 'F', value: 55, children: []},
        {
            name: 'G', value: 65,
            children: [
                {name: 'H', value: 21, children: []},
                {name: 'I', value: 33, children: []}
            ]
        }
    ]
};

function find(node, value) {
    if (node.value === value) {
        return node;
    } else {
        for (let i = 0; i < node.children.length; i++) {
            let found = find(node.children[i], value);
            if (found !== null) {
                return found;
            }
        }

        return null;
    }
}

console.log(find(tree, 21).name);

https://blog.angularindepth.com/learn-recursion-in-10-minutes-e3262ac08a1

Dijkstra 是对的?

需要 登录 后方可回复, 如果你还没有账号请 注册新账号