Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

counting number of leaf nodes in binary tree

Tags:

binary-tree

I want to count the no of leaf nodes: Note:Cannot use global/class level variable I implmeted following algo, and it works fine.But i want method signature to be

countLeaves(Node node)

I know that i can overload methds and call the 2 args method sig from 1 args, but dont want to do so.Can anyone suggest any other method?

int countLeaves(Node node,int count){
        if(node==null)
            return 0;

        if(node.left==null && node.right==null){
            return 1+count;
        }else{
            int lc = countLeaves(node.left, count);
            int total = countLeaves(node.right, lc);
            return total;
        }
    }
like image 848
dojoBeginner Avatar asked May 10 '11 12:05

dojoBeginner


1 Answers

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

You are doing the same thing as before but instead of holding the current count as we go, we simply say return the result of the sum of the left and right node. These in turn recurse down till they hit the basecases.

like image 66
Mike Kwan Avatar answered Dec 11 '22 08:12

Mike Kwan