开发者

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 inst开发者_Python百科ead I get 4 left-child nodes.


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;
}


To count left-child nodes you can do:

private int countLeftNodes(IntTreeNode node) {

    // no tree no left-child nodes      
    if(node == null) {
       return 0;
    }

    // left-child count of current node.
    int c = 0;

    // does the current node have a left-child ?
    if (node.left != null){
      c = 1;
    }

    // return left-child count of current node +
    // left-child count of left and right subtrees
    return c + countLeftNodes(node.left) + countLeftNodes(node.right);
}


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

    return c;
}


easiest place to check that is in the parent.

private int countLeftNodes(IntTreeNode node){

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

    return c;
}


My favorite style when using recursion is to use a wrapper function of some sort where the main method calls another that does the grunt work:

private int countLeftNodes(IntTreeNode node){
   int totalCount = reallyCountLeftNodes(IntTreeNode node, 0); 
   return totalCount;
}

private int reallyCountLeftNodes(IntTreeNode n, Int sum){
    if (n.left == NULL && n.right == NULL){  //check if we've hit rock bottom
        return sum;
    } else if (n.left == NULL) { //if the node's left is nil, go right
        reallyCountLeftNodes(n.right, sum++);   
    } else {
        reallyCountLeftNodes(n.left, sum++);  // Going as far left as possible!
    }
}

Notice how the main function calls another. I find this style to be cleaner and easier to understand. Also, the second function has a count variable for you to use.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜