Home > Software design >  How to print all the nodes number of a tree
How to print all the nodes number of a tree

Time:10-30

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. 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

CodePudding user response:

You can do this using a for loop and recursion.

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)
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related