Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting left-child nodes in a Tree

I am supposed to implement a recursive method that counts the amount of left-child tree nodes. My code so far is:

private int countLeftNodes(IntTreeNode node){
    int c = 0;
    if (node != null){
        c = 1 + countLeftNodes(node.left);
        countLeftNodes(node.right);
    }

    return c;
}

It returns a number much smaller than what it should be. I have a feeling that my traversal is off because it seems to only count the very left child nodes, and then terminates. When I call this method on an IntTree of size 16 I should get 8 left-child nodes, 7 right-child nodes, and one root, but instead I get 4 left-child nodes.

like image 271
Shane Avatar asked Dec 17 '22 16:12

Shane


1 Answers

You never count the left nodes in the right tree.

private int countLeftNodes(IntTreeNode node)
{
    int c = 0;
    if (node.left != null)
    {
        c += 1 + countLeftNodes(node.left);
    }
    if(node.right != null)
    {
        c += countLeftNodes(node.right);
    }

    return c;
}
like image 61
Endophage Avatar answered Dec 29 '22 09:12

Endophage