My class is currently doing Binary Trees as part of our data structures unit. I understand that the Node class must have 3 parameters (value, left node, right node) in its constructor. As part of a requirement, we must have a Tree class. What is the purpose of a tree class? Is it for managing the entire set of Nodes? Does it simply contain the functions necessary to insert, remove and search for specific Nodes?
Thank you in advance.
My Node class:
class Node {
protected int data;
protected leftNode;
protected rightNode;
Node (int data, Node leftNode, Node rightNode){
this.data = data;
this.leftNode = leftNode;
this.rightNode = rightNode;
}
}
The assumption is, as you suspect, a little bit flawed. The
Nodetype that you have defined is a perfectly fine instance of a binary tree.Jack mentions that you want to have a
Treetype around the whole set of nodes in order to provide operations likegetRoot, inserts, deletes and so on. This is of course not a bad idea, but it is by no means a requirement. Many of these operations could go onNodeitself, and you don’t necessarily have to have all of these operations; for example, there are arguments both for and against having agetRootoperation. An argument against it is that if you have an algorithm that at one point only needs a subtree, then theTreeobject that holds on to the rootNodeprevents garbage collection ofNodes that your algorithm no longer needs.But more generally, the real question that needs to be asked here is this: which of the things you’re dealing are interface, and which are implementation? Because it’s one thing if you want to expose binary trees as an interface to callers, and another if you want to provide some sort of finite map as the interface, and the binary tree is just an implementation detail. In the former case, the client would “know” that a tree is either
nullor aNodewith a value and branches, and would be allowed to, for example, recurse on the structure of the tree; in the latter case, all that the client would “know” is that your class supports some form ofput,getanddeleteoperations, but it’s not allowed to rely on the fact that this is stored as a search tree. In many variants of the latter case you indeed would use aTreetype as a front end to hide the nodes from the clients. (For example, Java’s built-injava.util.TreeMapclass does this.)So the shortest answer is, really, it depends. The slightly longer answer is it depends on what the contract is between the binary tree implementation and its users; what things are the callers allowed to assume about the trees, what details of the binary tree are things that the author expects to be able to change in the future, etc.