How could I SUM every children in a tree with java recursion

De openkb
Aller à : Navigation, rechercher

Sommaire

Questions

So there s the mission. We have a class, call "Node", the instance is "node". This node has a lot of children, and these children have a lot of children too, etc etc. How could I SUM the all children number in this tree? example:

    • node -> child1 -> child1.1 -> child1.1.1, child 1.1.2 -> child1.1.2.1
    • node -> child2
    • node -> child3 -> child3.1, child3.2 -> child3.2.1

the number of the all children is 10 (node is the parent). please help me someone, and write the current answer with java recursion. The program should start with:

public int childrenNumber(Node node){...

Answers

    • Create a function that s a member of your node class.
    • In the function, set a count variable to 1 (for this node).
    • Loop though all of this node s children. Add to the count variable the result of calling this function on each child node.
    • Return the count variable.

Now, to get the total number of nodes in the tree, call the count function on the root node.

Source

License : cc by-sa 3.0

http://stackoverflow.com/questions/12778791/how-could-i-sum-every-children-in-a-tree-with-java-recursion

Related

Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Outils