How to Perform Tree Operations in Java
In Computer Science, a tree is a data structure that can contain elements of an arbitrary type. The tree supports diverse retrieval methods, such as finding the element with a given value, or the elements smaller than a given value, or retrieving all elements in order. You can use the TreeSet class (pre-defined in the Java standard class libraries) to perform tree operations in your Java code.
Instructions
-
-
1
Insert the following line at the beginning of your Java code:
import java.util.*;
-
2
Populate a TreeSet object by declaring it, then inserting some elements--as in the following sample code:
TreeSet <Integer>myTree = new TreeSet<Integer>;
myTree.add(9);
myTree.add(2);
myTree.add(-1);
The sample tree has Integer elements (you can use any Java reference type): 9, 2 and -1.
-
-
3
Determine if an element is present in the TreeSet, as in the following sample code:
myTree.contains(new Integer(4));
The sample expression will evaluate to "false", as the object has not been added to the tree.
-
4
Remove an element known to be in the tree, as in the following sample code:
Integer myFour = new Integer(4);
myTree.add(myFour);
myTree.remove(myFour);
-
1