How to calculate leaf nodes in a nested data structure in Java?

I have a structure like we will call Box objects.

Box--+---Box----Box
     |
     +---Box-+--Box
             |
             +--Box
             |
             +--Box

I am trying to set a top box object for a list of leaf node blocks, which in this case are 3 block objects.

The box object has a list of its children in an instance variable of type Vector, called children.

The number of children can be unlimited.

I am trying to write one recursive method for this, but to no avail.

+3
source share
3 answers

One way to do this is to recursively traverse the structure. The idea is this:

  • There are no leaf nodes in an empty tree.
  • In a tree with root r without children, then r is the only leaf.
  • r, r , .

:

void findChildren (Box current, List<Box> found) {
    /* Case 1. */
    if (current == null) return;

    /* Case 2. */
    if (current.children.isEmpty()) {
        found.add(current);
        return;
    }

    /* Case 3. */
    for (Box child: current.children)
        findChildren(child, found);
}

, !

+1

, Java, , , , ; . , :

vector<Box> getLeaves(Box root)
{
    vector<Box> tempList;    //vector to hold nodes to check
    vector<Box> tempList2;   //vector to hold nodes' children
    vector<Box> leafList;
    bool goflag = true;

    tempList.add(root);

    while(goflag){
        for(int i = 0; i < tempList.size; i++){
            if(tempList[i].children.isEmpty()){
                leafList.add(tempList[i]);
            }
            else{
                //add all children to tempList2
                for(int c = 0; c < tempList[i].children.size; c++){
                    tempList2.add(tempList[i].children[c])
            }
        }
        if(tempList2.isEmpty()) //no more childs
            goflag = false;
        else
            tempList = tempList2;
        tempList2.clear();
    }
    return leafList;
}

, , .

+1

. .

  • , node .
  • , node. , , node , .
  • node , , .
  • , node .
  • , , .

, . , .

+1

Source: https://habr.com/ru/post/1790106/


All Articles