javarecursionbinary-treeparent-node

Counting the inner nodes (parent nodes) in a binary tree recursively


I need to create a recursive method that takes as a parameter the root node of a binary search tree. This recursive method will then return the int value of the total number of inner nodes in the entire binary search tree.

This is what I have so far:

int countNrOfInnerNodes (Node node) {
    if(node == null) {
       return 0;
    }
    if (node.left != null && node.right != null){
       return 1;
    }
    return countNrOfInnerNodes(node.left)+countNrOfInnerNodes(node.right)
    }
 }

Is there a better way? I also stuck to find a iterativ solution.


Solution

  • Here's the recursive method fixed:

    int countNrOfInnerNodes (Node node) {
        if(node == null) {
           return 0;
        }
    
        if (node.left == null && node.right == null) {
           // not an inner node !
           return 0;
        } else {
           // the number of inner nodes in the left sub-tree + the number of inner
           // nodes in the right sub-tree, plus 1 for this inner node
           return countNrOfInnerNodes(node.left) + countNrOfInnerNodes(node.right) + 1;
        }
    }
    

    Here's the iterative method:

    int countNrOfInnerNodes(Node node) {
        if (node == null)
            return 0;
    
        Stack<Node> nodesToCheck = new Stack<Node>();
    
        nodesToCheck.push(node);
        int count = 0;
    
        while (!nodesToCheck.isEmpty()) {
            Node checkedNode = nodesToCheck.pop();
            boolean isInnerNode = false;
    
            if (node.left != null) {
                isInnerNode = true;
                nodesToCheck.push(node.left);
            }
    
            if (node.right != null) {
                isInnerNode = true;
                nodesToCheck.push(node.right);
            }
    
            if (isInnerNode)
                count++;
        }
    
        return count;
    }