簡體   English   中英

如何打印樹的所有節點數

[英]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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM