简体   繁体   中英

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

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

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, ie

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM