如何打印树的所有节点数

How to print all the nodes number of a tree

我想打印这棵树中的所有“数量”元素,但据我测试,如果节点有超过 2 个孩子,它不会打印其他的,就像在下面的输出,我 运行 没主意了。 这是我的实际代码:

function preOrder(tree) {
    var qntChildren = 0

    try{
        console.log(tree.quantity)
        if (tree.childrens || tree.quantity) {
            preOrder(tree.childrens[0])
        }
    }catch(e) {
        preOrder(tree.childrens[qntChildren + 1])
    }

}

preOrder(treeModel)

这是树:

var treeModel = {
    "quantity": 5,
    "childrens": [

        {
        "quantity": 3,
        "childrens": [

            {
            "tech": "B",
            "quantity": 1,
            "childrens": []
                        },
            {
            "tech": "C",
            "quantity": 4,
            "childrens": []
                        },
            {
            "tech": "C",
            "quantity": 6,
            "childrens": []
            }
                    ]
            }
    ]
}

输出为:

5
3
1
4
c:\Users\gabri\Área de Trabalho\Estágio\Arvore.js:41
        preOrder(tree.childrens[qntChildren + 1])
                      ^

TypeError: Cannot read property 'childrens' of undefined
    at preOrder (c:\Users\gabri\Área de Trabalho\Estágio\Arvore.js:41:23)
    at preOrder (c:\Users\gabri\Área de Trabalho\Estágio\Arvore.js:41:9)
    at Object.<anonymous> (c:\Users\gabri\Área de Trabalho\Estágio\Arvore.js:46:1)
    at Module._compile (internal/modules/cjs/loader.js:1063:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
    at Module.load (internal/modules/cjs/loader.js:928:32)
    at Function.Module._load (internal/modules/cjs/loader.js:769:14)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)
    at internal/main/run_main_module.js:17:47

您可以使用 for 循环和递归来完成此操作。

var treeModel = { quantity: 5, childrens: [ { quantity: 3, childrens: [ { tech: 'B', quantity: 1, childrens: [] }, { tech: 'C', quantity: 4, childrens: [] }, { tech: 'C', quantity: 6, childrens: [] }, ], }, ], };

function getQuantity(tree) {
  console.log(tree.quantity);
  for (const child of tree.childrens) getQuantity(child);
}

getQuantity(treeModel)