【问题标题】:How to print all the nodes number of a tree如何打印树的所有节点数
【发布时间】:2021-10-29 20:12:40
【问题描述】:

我想打印这棵树中的所有“数量”元素,但据我测试,如果节点有超过 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

【问题讨论】:

    标签: javascript arrays tree


    【解决方案1】:

    您可以使用 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)

    【讨论】:

      猜你喜欢
      • 2019-05-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-15
      相关资源
      最近更新 更多