Recursively counting special nodes in a tree

I built a tree consisting of nodes with each node having an attribute and a list of successors. I am trying to implement a recursive function that starts to move through the tree for a given node (in this example, in the node "Method"). The function should count the number of nested nodes with the given attribute. In the end, I want to return the largest number found in one branch. Speaking about this example, I would like to find the maximum number of nested nodes with the attribute "Loop", which will be equal to 3 (the corresponding branch is marked in orange).

Example: enter image description here Currently, my approach is as follows:

private static int getLNDforMethod(DirectedNodeInterface curNode, int currentLND) {

    NodeIterator successors = curNode.getSuccessors();
    while(successors.hasNext())
    {
        successors.next();
        DirectedNodeInterface curSuc = (DirectedNodeInterface) successors.getNode();

        // isLoop returns true if the given node is a loop
        if(isLoop(curSuc))
        {
            ++currentLND;
        }

        currentLND = getLNDforMethod(curSuc, currentLND);
    }

    return currentLND;
}

, , . , 3 ( , ), 7 , "" .

-, . - ?

+4
3

- , . , , max . (, , ), max , max, max , node .

:

  • max, , 0
  • own , node, 0, 1, node
  • getLNDforMethod childMax
  • max max own+childMax
  • max

Java-:

private static int getLNDforMethod(DirectedNodeInterface curNode) {
    int max = 0;
    int own = isLoop(curNode) ? 1 : 0;
    NodeIterator successors = curNode.getSuccessors();
    while(successors.hasNext()) {
        successors.next();
        DirectedNodeInterface curSuc = (DirectedNodeInterface) successors.getNode();
        max = Math.max(max, own + getLNDforMethod(curSuc));
    }
    return max;
}
+5
private static int getLNDforMethod(DirectedNodeInterface curNode) {

    int maxChild = 0;
    NodeIterator successors = curNode.getSuccessors();
    while(successors.hasNext())
    {
        successors.next();
        DirectedNodeInterface curSuc = (DirectedNodeInterface) successors.getNode();
        maxChild = Math.max(maxChild, getLNDforMethod(curSuc));
    }

    return maxChild + (isLoop(curNode) ? 1 : 0);
}
+3

, , . , , - LOOP , , , LOOP . , .

private static int GetLNDForMethod(DirectedNodeInterface curNode) {
    NodeIterator successors = curNode.getSuccessors();
    unsigned int numLnds = 0;
    while (successors.hasNext()) {
        successors.next();
        DirectedNodeInterface curSuc = (DirectedNodeInterface) successors.getNode();

        unsigned int curLnds = GetLNDForMethod(curSuc);
        if (isLoop(curSuc))
            curLnds++;
        if (numLnds < curLnds)
            numLnds = curLnds;
    }

    return numLnds;
}

, , , , , .

, ( ) node, , , node LOOP

+2
source

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


All Articles