Recitation 10

Introduction

In this recitation, you will practice building a tree and traversing it to count the number of leaves in the tree. Building a tree is not as straight forward as adding a value to the other data structures we've seen so far, so working through how to build (or add to) trees will be useful to practice. Tree traversal is a very common action since so many tree operations depend on it so once your tree is built, you will traverse it to count the number of leaves.

Tree

We haven't seen a complete Node class for trees yet. Use the Node class below to represent your tree. Note: this is for a generic tree, not binary trees (which we're looking at in lecture this week). Do not modify the class below.

class TreeNode<T>
{
    private T value;
    private ArrayList<TreeNode<T>> children;
    
    public TreeNode(T val)
    {
        value = val;
        children = new ArrayList<TreeNode<T>>();
    }
    
    public T getValue()
    {
        return value;
    }
    
    public void setValue(T val)
    {
        value = val;
    }
    
    public void addChild(TreeNode<T> child)
    {
        children.add(child);
    }
    
    public void addChild(int position, TreeNode<T> child)
    {
        children.add(position, child);
    }
    
    public TreeNode<T> getChild(int position)
    {
        return children.get(position);
    }
    
    public TreeNode<T> removeChild(int position)
    {
        return children.remove(position);
    }
    
    public int numberOfChildren()
    {
        return children.size();
    }
}

Tree to Build

Use the Node class above to construct the tree shown below (which comes from our lecture notes):

Tree Operation

Implement the operation below on the tree described below.

Conceptual Question

Is is possible for a node to be both a root and a leaf in the same tree? Explain your answer.

Submission and Grading

This is for your practice. You should be able to complete some of the functions by the end of recitation. If you complete a function, call the TA over to look over your function to make sure it is correct. If you do not have time to complete the programs before the end of recitation, you have the option of uploading it to CourseWeb once you are finished to receive feedback on it from the TA. If you upload it after Monday, November 23, please email the TA so he knows to look at it.