[to understand the context of this problem, you should read the class #07 exercise sheet]


[AED039] Counting Leaves

In this problem you should only submit a binaryTree.h file with a self-containing definition of a class BTree<T>

Base Code

Use as a basis the class BTree<T> (see code | download code) which implements a generic binary tree that was explained in classes, with methods to read a tree from standard input, to write several node traversals, to count the number of nodes, to compute the height and to see if it contains a certain value.

The Problem

Add a new method int numberLeaves() const to the class. The method does not change the tree, so it should be const (as seen in the lectures). The function should return the number of leaves of the tree. Recall that a leaf is a node with no children nodes. For instance, the trees in the following have respectively 4, 3 and 1 leaves (indicated in yellow).

Submission

You should submit the file binaryTree.h with the method numberLeaves added to binaryTree<T> as requested (and without removing any of the other existing methods). You can however create additional methods, if you need them.

Mooshak will use the following code to link to your class, read the inputs, build the trees and call your method, printing its result.

#include <iostream>
#include <string>

#include "binaryTree.h"

// Read a tree of type t assuming "N" as the null value
// call t.numberLeaves() method and write its output
template <typename T>
void read() {
  BTree<T> t;
  t.read("N");

  std::cout << "t.numberLeaves() = " << t.numberLeaves() << std::endl;
}

int main() {

  int n;
  std::cin >> n;
  for (int i=0; i<n; i++) {
    std::string type;
    std::cin >> type;
    if (type == "int") read<int>();
    else if (type == "string") read<std::string>();
  }
  
  return 0;
}

Example Input Example Output
3

int
6 3 2 N N 5 N N 10 8 N N 25 N N

int
6 3 2 N N 5 N N 10 N N

int
6 3 N N N

t.numberLeaves() = 4
t.numberLeaves() = 3
t.numberLeaves() = 1

The example input corresponds to the trees in the example figure given in the problem description.



Algorithms and Data Structures (L.EIC011) 2026/2027
DCC/FCUP & DEI/FEUP - University of Porto