Compute number of leaves in binary tree recursively

93 Views Asked by At
ALGORITHM LeafCounter(BTNode node) 
  // Computers recursively the number of leaves in a binary tree
  // Input: Root node of a binary (sub-)tree 1/ 
  // Output: The number of leaves in the tree rooted by input node
  if (node == null) return 0;
  else 
    return LeafCounter(node.getLeftChild 0 ) + Leaf Counter(node.getRightChild();

I am not sure how to edit this so it will accurately count leaves? Also, if you could supply proof of why this fails it would be very helpful as to me, it looks like it should be working

2

There are 2 best solutions below

0
On

Correct Algorithm:

ALGORITHM LeafCounter(BTNode node) 
  // Computers recursively the number of leaves in a binary tree
  // Input: Root node of a binary (sub-)tree 1/ 
  // Output: The number of leaves in the tree rooted by input node
  if (node == null) return 0;
  else 
    //Since current node is not null so 
    return 1 + LeafCounter(node.getLeftChild()) + Leaf Counter(node.getRightChild());

Note:You may need to subtract 1 from final result, to exclude the root node from count.

0
On

You just need to check for the leaf condition, to give correct results.

ALGORITHM LeafCounter(BTNode node) 
  // check base condition
  if (node == null) return 0;
  // check leaf condition
  if (node.getLeftChild() == null && node.getRightChild() == null) return 1;
  // recurse for children
  else return LeafCounter(node.getLeftChild()) + LeafCounter(node.getRightChild());