Thursday, March 3, 2016

CS 2420 - Assignment 5 - Part 1

So even though there is no assignment this week, I asked the professor to post the next assignment early. It turns out that writing my Linked List class a few days ago was a good call, because the next assignment will be Trees!

The assignment will have us built two trees: a Binary Search Tree and a Binary Expression Tree.

I have started working on both, but I have been mainly focusing on the BS Tree since to me its the easiest of the two. I am actually almost done with the BS Tree, here is what I have:

class BinarySearchTree
{
    public TreeNode root;
    private int node_count;

    public BinarySearchTree()
    {
        root = null;
        node_count = 0;
    }

    public void Add(int item)
    {
        TreeNode new_node = new TreeNode(item);
        if (root == null)
            root = new_node;
        else
        {
            TreeNode crawler = root;

            while (crawler != null)
            {
                new_node.parent = crawler;
                if (item >= crawler.data)
                    crawler = crawler.right;
                else
                    crawler = crawler.left;
            }

            if (item >= new_node.parent.data)
                new_node.parent.right = new_node;
            else
                new_node.parent.left = new_node;
        }
        node_count++;
    }

    public bool Contains(int item)
    {
        TreeNode crawler = root;
        while (crawler != null)
        {
            if (item == crawler.data)
                return true;
            else if (item >= crawler.data)
                crawler = crawler.right;
            else
                crawler = crawler.left;
        }
        return false;
    }

    public void Clear()
    {
        root = null;
        node_count = 0;
    }

    public int NodeCount
    {
        get
        {
            return node_count;
        }
    }

    public void TraversePre(MyList list, TreeNode node)
    {
        list.Add(node.data);
        if (node.left != null)
            TraversePre(list, node.left);
        if (node.right != null)
            TraversePre(list, node.right);
    }

    public void TraverseIn(MyList list, TreeNode node)
    {
        if (node.left != null)
            TraverseIn(list, node.left);
        list.Add(node.data);
        if (node.right != null)
            TraverseIn(list, node.right);
    }

    public void TraversePost(MyList list, TreeNode node)
    {
        if (node.left != null)
            TraversePost(list, node.left);
        if (node.right != null)
            TraversePost(list, node.right);
        list.Add(node.data);
    }
}

My Binary Search Tree takes advantage of the List class I wrote for assignment 4 and of a Node class that has only three properties: Left, Right, & Parent. That's all for now, thanks for reading!

No comments:

Post a Comment