ekim6755
ekim6755

Reputation: 5

Recursively count the number of leaves in a binary tree without given parameters

I am struggling to figure out how to code a recursive algorithm to count the number of leaves in a Binary Tree (not a complete tree). I get as far as traversing to the far most left leaf and don't know what to return from there. I am trying to get the count by loading the leaves into a list and getting the size of that list. This is probably a bad way to go about the count.

    public int countLeaves ( ) {

    List< Node<E> > leafList = new ArrayList< Node<E> >();
    //BinaryTree<Node<E>> treeList = new BinaryTree(root);

    if(root.left != null) 
    {
        root = root.left;
        countLeaves();
    }
    if(root.right != null) 
    {
        root = root.right;
        countLeaves();
    }
    if(root.left == null && root.right == null) 
    {
        leafList.add(root);
    }


        return();
}

Upvotes: 0

Views: 4170

Answers (2)

MSameer
MSameer

Reputation: 443

Elaborating on @dasblinkenlight idea. You want to recursively call a countleaves on root node & pass back the # to caller. Something on the following lines.

public int countLeaves() {
 return countLeaves(root);
 }

/**
 * Recursively count all nodes
 */
private static int countLeaves (Node<E> node) {
 if(node==null)
   return 0;

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

Edit: It appears, a similar problem was previously asked counting number of leaf nodes in binary tree

Upvotes: 2

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726569

The problem with your implementation is that it does not restore the value of member variable root back to the state that it had prior to entering the method. You could do it by storing the value in a local variable, i.e.

Node<E> oldRoot = root;
... // your method goes here
root = oldRoot;

However, a better approach is to take Node<E> as an argument, rather than relying on a shared variable:

public int countLeaves() {
    return countLeaves(root);
}

private static int countLeaves (Node<E> node) {
    ... // Do counting here
}

Upvotes: 1

Related Questions