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