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


i struggling figure out how code recursive algorithm count number of leaves in binary tree (not complete tree). far traversing far left leaf , don't know return there. trying count loading leaves list , getting size of list. bad way go 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. want recursively call countleaves on root node & pass # caller. on following lines.

public int countleaves() {  return countleaves(root);  }  /**  * recursively count 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: appears, similar problem asked counting number of leaf nodes in binary tree


Comments

Popular posts from this blog

Ansible - ERROR! the field 'hosts' is required but was not set -

customize file_field button ruby on rails -

SoapUI on windows 10 - high DPI/4K scaling issue -