简体   繁体   English

如何打印树的所有节点数

[英]How to print all the nodes number of a tree

I want to print all the "quantity" elements inside this tree, but as far as i've tested it, if the node has more than 2 childrens, it will just not print the other ones, like in the output below, i'm running out of ideas.我想打印这棵树内的所有“数量”元素,但据我测试,如果节点有 2 个以上的孩子,它不会打印其他的,就像下面的输出一样,我我的想法不多了。 This is my actual code:这是我的实际代码:

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)

This is the tree:这是树:

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

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

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

The output is:输出是:

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

You can do this using a for loop and recursion.您可以使用 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM