Counting the leaves

Chapter: Counting the leaves

A node in a binary tree is called a leaf if both its children are empty.


Exercise 8

Write an abstract method int countLeaves() for the ATree class, and concrete methods int countLeaves() for the ETree and ATree classes to count the number of leaves in a tree. Add a button labeled "count leaves" to the TestTree class and make it work correctly.

Now let's see if we can formulate a guess as to the "big O" count of how many leaves we can expect in a tree with n nodes.


Exercise 9

Use hamlet.txt and the five files you used previously. Read them in to your new TestTree program and record the number of nodes and the number of leaves for each tree. Plot the number of leaves (y axis) against the number of nodes (x axis). Formulate and state a reasonable hypothesis relating the number of leaves to the number of nodes in a binary search tree built from essentially random data.

But what if your input data is not essentially random?


Exercise 10

Input the data from mystery.txt into your new TestTree. Count the number of nodes and the number of leaves. Does this pair fit well with the data you have for your graph from the previous exercise? Explain.


rhyspj@gwu.edu