Tuesday, January 13, 2015

Examples and Notes on Trees

A tree, continuing on from linked lists, is a data structure used in Java. It starts with the initial node, called the root, and then contains several nodes that may contain references to many other nodes. The initial nodes are considered roots of subtrees. It is described on Wikipedia here, however this description isn't entirely Java-based, rather just of the general programming concept of Trees. A good example of a tree would be the image below:

20 would be the root, or initial node, and number 15 would be the left node and 30 would be the right node. This has the ability to continue as long as the developer would like, and allows for quick sorting and accessing of data.

A good example of a tree can be seen from the example below, taken from EIMACS:

public class TreeNode
{
private Object value;
private TreeNode left;
private TreeNode right;
public TreeNode( Object initValue )
{
value = initValue;
left = null;
right = null;
}
public TreeNode( Object initValue,
TreeNode initLeft,
TreeNode initRight )
{
value = initValue;
left = initLeft;
right = initRight;
}
public Object getValue() { return value; }
public TreeNode getLeft() { return left; }
public TreeNode getRight() { return right; }
public void setValue( Object newValue )
{
value = newValue;
}
public void setLeft( TreeNode newLeft )
{
left = newLeft;
}
public void setRight( TreeNode newRight )
{
right = newRight;
}
}

As seen, this class allows for tree nodes to be modified and created. If used properly, it will allow for the full creation of a binary tree!

The setLeft and setRight methods allow for creation of the left and right children, respectively. setValue allows for a certain value to be reset, and getValue is a getter method to find a certain value. Although it's a bit more complex than the previously explained searching and sorting methods, once you understand it, you'll have a much better way to set, sort, and access data.

1 comment:

  1. Trees are not Java based at all, Finn. Java is just one of a myriad of languages (any general purpose programming language will do) that can be used to implement trees.

    To be clear, you are learning about a *data structure* (see http://xlinux.nist.gov/dads/HTML/datastructur.html), which is independent of any implementation. Data structures Algorithms is what second semester CS is all about. I encourage you to look on the book shelf behind where you sit and glance over the Data Structures in C book that Sam was using.

    It would also be helpful to look at the NIST site for a definition of Abstract Data Type (http://xlinux.nist.gov/dads/HTML/abstractDataType.html).

    Assignment: Write a blog post next week in which you define "abstract data type" in your own words. Be sure to list examples of ADTs.

    ReplyDelete