Unit 5 General Tree Algorithm Review Discussion Question
Using Jeliot, execute the following tree algorithm:
import Prog1Tools.IOTools; class Node { Node left; Node right; int value;
public Node(int value) { this.value = value; } }
public class GeneralTreeTest { public static void main(String[] args) {
// build a simple tree add 5 nodes to the tree Node root = new Node(5); System.out.println("Tree Example"); System.out.println("Building tree with root value " + root.value); insert(root, 1); insert(root, 8); insert(root, 6); insert(root, 3); …show more content…
insert(root, 9); System.out.println("Traversing tree "); printOrder(root);
}
public static void insert(Node node, int value) { if (value < node.value) { if (node.left != null) { insert(node.left, value); } else { System.out.println(" Inserted " + value + " to left of " + node.value); node.left = new Node(value); } } else if (value > node.value) { if (node.right != null) { insert(node.right, value); } else {
System.out.println(" Inserted " + value + " to right of " + …show more content…
Using the Jeliot environment, load, compile and execute this java algorithm to understand its operation. Determine the kind of tree structure that is being created and determine what kind of traversal the algorithm is conducting.
After loading, compiling and executing the given java algorithm, I found out that the output was in order of increasing number- (1, 3, 6, 8, 9). This means that this type of tree store element in such a way that their “natural order” is preserved; the largest (or the smallest) can be retrieved quickly; and it presents relationships/connections between elements in the collection.
This tree is a binary search tree which is an ordered binary tree. Every node in the tree is greater than each element in its left subtree and less than each element in its right subtree. By performing inorder traversal, we can get the values in sorted order.
Starting at the root:
• Visit the left subtree
• Visit the node
• Visit the right