Sunday, December 30, 2012

TreeApp.java

class Node {
   public int iData;
   public Node leftChild;
   public Node rightChild;
}

class Tree {
   private Node root;

   public Tree() {
   root = null;

   }

   public void insert(int id) {

   Node newNode = new Node();

   newNode.iData = id;

   if (root == null) {

   root = newNode;

   }

   else {

   Node current = root;

   Node parent;

   while (true) {

   parent = current;

   if (id < parent.iData) {

   current = current.leftChild;

   if (current == null) {

   parent.leftChild = newNode;

   return;

   }

   }

   else {

   current = current.rightChild;

   if (current == null) {

   parent.rightChild = newNode;

   return;

   }

   }

   }// end while

   }// end else not root

   }// end insert

   public Node find(int key) {

   Node current = root;

   while (current.iData != key) {

   if (key < current.iData) {

   current = current.leftChild;

   }

   else {

   current = current.rightChild;

   }

   if (current == null) {

   return null;

   }

   }

   return current;

   }

   public void traverse(int traverseType) {

   switch (traverseType) {

   case 1:

   System.out.println("Preorder traversal:");

   preOrder(root);

   break;

   case 2:

   System.out.println("Inorder traversal:");

   inOrder(root);

   break;

   case 3:

   System.out.println("Postorder traversal:");

   postOrder(root);

   break;

   }

   }

   private void preOrder(Node localRoot) {

   if (localRoot != null) {

   System.out.println(localRoot.iData + " ");

   preOrder(localRoot.leftChild);

   preOrder(localRoot.rightChild);

   }

   }

   private void inOrder(Node localRoot) {

   if (localRoot != null) {

   inOrder(localRoot.leftChild);

   System.out.println(localRoot.iData + " ");

   inOrder(localRoot.rightChild);

   }

   }

   private void postOrder(Node localRoot) {

   if (localRoot != null) {

   postOrder(localRoot.leftChild);

   postOrder(localRoot.rightChild);

   System.out.println(localRoot.iData + " ");

   }

   }
}

class TreeApp {
   public static void main(String[] args) {
   Tree theTree = new Tree();

   theTree.insert(50);

   theTree.insert(25);

   theTree.insert(75);

   theTree.insert(12);

   theTree.insert(37);

   theTree.insert(43);

   theTree.insert(30);

   theTree.insert(33);

   theTree.insert(87);

   theTree.insert(93);

   theTree.insert(97);

   theTree.traverse(3);

   }
}

No comments:

Post a Comment