Advertisement
Guest User

BST java hw #18

a guest
Dec 19th, 2014
185
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 10.86 KB | None | 0 0
  1. /*
  2. * Max Bratnichenko
  3. * CSCI-401
  4. * Height and Breafth in BST
  5. */
  6.  
  7. //HeightandBFT
  8. public class HeightBFT
  9. {
  10.     //main method
  11.     public static void main(String[]args)
  12.     {
  13.         //Create an object for BST of type String
  14.         BST<String> stringTree = new BST<String>();
  15.         stringTree.insert("Max");
  16.         stringTree.insert("Tom");
  17.         stringTree.insert("Joe");
  18.         stringTree.insert("Ron");
  19.         stringTree.insert("Sue");
  20.         stringTree.insert("Cal");
  21.         stringTree.insert("Pat");
  22.        
  23.         //call the traversal methods of stringTree
  24.         System.out.print("Inorder (sorted): ");
  25.         stringTree.inorder ();
  26.         System.out.print("\n Postorder: ");
  27.         stringTree.postorder();
  28.         System.out.print("\n Preorder: ");
  29.         stringTree.preorder();
  30.        
  31.         //Calling the height method for tree of strings
  32.         System.out.print("\n Height of the tree is : "
  33.         + stringTree.height());
  34.        
  35.         //Calling the breadtFirstTraversal method for tree of strings
  36.         System.out.println("\n Breadth frist traversal: ");
  37.         stringTree.breadthFirstTraversal();
  38.        
  39.         //Creating object for BST
  40.         Integer[] numbers= {2,4,3,1,8,5,6,7};
  41.         BST<Integer> intTree = new BST<Integer>(numbers);
  42.        
  43.         //call traverse methods of intTree
  44.         System.out.println("\n Inorder (sorted): ");
  45.         intTree.inorder();
  46.         System.out.print("\n Postorder: ");
  47.         intTree.postorder();
  48.        
  49.         //call height method for tree of ints
  50.         System.out.print("\n Height of the tree: " + intTree.height());
  51.        
  52.         //call breadthFirstTraversal method free of ints
  53.         System.out.println("\n Breadth first traversal: ");
  54.         intTree.breadthFirstTraversal();
  55.        
  56.     }
  57. }
  58.  
  59. ///////////////////////////////////////////////////////////////////
  60.  
  61.  
  62.  
  63. import java.util.*;
  64.  
  65. public class BST<E extends Comparable<E>>extends AbstractTree<E>
  66. {
  67.     protected  TreeNode<E>  root;
  68.     protected static int size = 0;
  69.  
  70.     //Default binary search tree
  71.     public BST() {
  72.     }
  73.  
  74.     //binary search tree from an array of objects */
  75.     public BST(E[] objects) {
  76.         for (int i = 0; i < objects.length; i++)
  77.             insert(objects[i]);
  78.     }
  79.  
  80.  
  81.      // Return true if the element is in the tree */
  82.     public boolean search(E e) {
  83.         TreeNode<E> current = root; // Start from the root
  84.  
  85.         while (current != null) {
  86.             if (e.compareTo(current.element) < 0) {
  87.                 current = current.left;
  88.             } else if (e.compareTo(current.element) > 0) {
  89.                 current = current.right;
  90.             } else
  91.                 // element matches current.element
  92.                 return true; // Element is found
  93.         }
  94.  
  95.         return false;
  96.     }
  97.  
  98.     /**
  99.      * Insert element e into the binary search tree. Return true if the element
  100.      * is inserted successfully.
  101.      */
  102.    
  103.     public boolean insert(E e) {
  104.         if (root == null)
  105.             root = createNewNode(e); // Create a new root
  106.         else {
  107.             // Locate the parent node
  108.             TreeNode<E> parent = null;
  109.             TreeNode<E> current = root;
  110.             while (current != null)
  111.                 if (e.compareTo(current.element) < 0) {
  112.                     parent = current;
  113.                     current = current.left;
  114.                 } else if (e.compareTo(current.element) > 0) {
  115.                     parent = current;
  116.                     current = current.right;
  117.                 } else
  118.                     return false; // Duplicate node not inserted
  119.  
  120.             // Create the new node and attach it to the parent node
  121.             if (e.compareTo(parent.element) < 0)
  122.                 parent.left = createNewNode(e);
  123.             else
  124.                 parent.right = createNewNode(e);
  125.         }
  126.  
  127.         size++;
  128.         return true; // Element inserted
  129.     }
  130.  
  131.     protected TreeNode<E> createNewNode(E e) {
  132.         return new TreeNode<E>(e);
  133.     }
  134.     @Override/** Inorder traversal from the root */
  135.     public void inorder() {
  136.         inorder(root);
  137.     }
  138.  
  139.     /** Inorder traversal from a subtree */
  140.     protected void inorder(TreeNode<E> root) {
  141.         if (root == null)
  142.             return;
  143.         inorder(root.left);
  144.         System.out.print(root.element + " ");
  145.         inorder(root.right);
  146.     }
  147.  
  148.     @Override/** Postorder traversal from the root */
  149.     public void postorder() {
  150.         postorder(root);
  151.     }
  152.  
  153.     /** Postorder traversal from a subtree */
  154.     protected void postorder(TreeNode<E> root) {
  155.         if (root == null)
  156.             return;
  157.         postorder(root.left);
  158.         postorder(root.right);
  159.         System.out.print(root.element + " ");
  160.     }
  161.  
  162.     @Override/** Preorder traversal from the root */
  163.     public void preorder() {
  164.         preorder(root);
  165.     }
  166.  
  167.     /** Preorder traversal from a subtree */
  168.     protected void preorder(TreeNode<E> root) {
  169.         if (root == null)
  170.             return;
  171.         System.out.print(root.element + " ");
  172.         preorder(root.left);
  173.         preorder(root.right);
  174.     }
  175.  
  176.     /**
  177.      * This inner class is static, because it does not access any instance
  178.      * members defined in its outer class
  179.      */
  180.     public static class TreeNode<E extends Comparable<E>> {
  181.         protected E element;
  182.         protected TreeNode<E> left;
  183.         protected TreeNode<E> right;
  184.  
  185.         public TreeNode(E e) {
  186.             element = e;
  187.         }
  188.  
  189.         public int getSize() {
  190.             return size;
  191.         }
  192.  
  193.         /** Returns the root of the tree */
  194.         public TreeNode<E> getRoot() {
  195.             return root;
  196.         }
  197.  
  198.         /** Returns a path from the root leading to the specified element */
  199.         public java.util.ArrayList<TreeNode<E>> path(E e) {
  200.             java.util.ArrayList<TreeNode<E>> list = new java.util.ArrayList<TreeNode<E>>();
  201.             TreeNode<E> current = root; // Start from the root
  202.  
  203.             while (current != null) {
  204.                 list.add(current); // Add the node to the list
  205.                 if (e.compareTo(current.element) < 0) {
  206.                     current = current.left;
  207.                 } else if (e.compareTo(current.element) > 0) {
  208.                     current = current.right;
  209.                 } else
  210.                     break;
  211.             }
  212.  
  213.             return list; // Return an array of nodes
  214.         }
  215.  
  216.         /**
  217.          * Delete an element from the binary search tree. Return true if the
  218.          * element is deleted successfully. Return false if the element is not
  219.          * in the tree.
  220.          */
  221.         public boolean delete(E e) {
  222.             // Locate the node to be deleted and also locate its parent node
  223.              TreeNode<E> parent = null;
  224.              TreeNode<E> current = root;
  225.              while (current != null) {
  226.              if (e.compareTo(current.element) < 0) {
  227.              parent = current;
  228.              current = current.left;
  229.              }
  230.              else if (e.compareTo(current.element) > 0) {
  231.              parent = current;
  232.              current = current.right;
  233.              }
  234.              else
  235.              break; // Element is in the tree pointed at by current
  236.              }
  237.            
  238.              if (current == null)
  239.              return false; // Element is not in the tree
  240.            
  241.              // Case 1: current has no left children
  242.              if (current.left == null) {
  243.                 // Connect the parent with the right child of the current node
  244.                  if (parent == null)
  245.                      root = current.right;
  246.                       else {
  247.                       if (e.compareTo(parent.element) < 0)
  248.                      parent.left = current.right;
  249.                       else
  250.                       parent.right = current.right;
  251.                       }
  252.                       }
  253.                       else {
  254.                       // Case 2: The current node has a left child.
  255.                       // Locate the rightmost node in the left subtree of
  256.                       // the current node and also its parent.
  257.                       TreeNode<E> parentOfRightMost = current;
  258.                       TreeNode<E> rightMost = current.left;
  259.                      
  260.                       while (rightMost.right != null) {
  261.                       parentOfRightMost = rightMost;
  262.                       rightMost = rightMost.right; // Keep going to the right
  263.                       }
  264.                      
  265.                       // Replace the element in current by the element in rightMost
  266.                       current.element = rightMost.element;
  267.                      
  268.                       // Eliminate rightmost node
  269.                       if (parentOfRightMost.right == rightMost)
  270.                       parentOfRightMost.right = rightMost.left;
  271.                       else
  272.                       // Special case: parentOfRightMost == current
  273.                       parentOfRightMost.left = rightMost.left;
  274.                       }
  275.                      
  276.                       size --;
  277.                       return true; // Element deleted
  278.                       }
  279.  
  280.         ///////////////////////BreadthFirstTraversal Method//////////////////////
  281.         //Displays elements of tree in order, level by level
  282.         public void breadthFirstTraversal()
  283.         {
  284.             List<TreeNode<E>> list=new
  285.                     ArrayList<TreeNode<E>>();
  286.             if(root != null)
  287.                 list.add(root);
  288.            
  289.             TreeNode<E> current;
  290.            
  291.             while(!list.isEmpty()){
  292.                 current= (TreeNode<E>)list.remove(0);
  293.                 //display the element of the tree
  294.                 System.out.print(current.element + "");
  295.                
  296.                 if(current.left != null)
  297.                     list.add(current.left);
  298.                 if(current.right != null)
  299.                     list.add(current.right);       
  300.             }
  301.         }
  302.        
  303.         ///////////////////////////Height Method///////////////////////
  304.         //Find and return the height of the tree
  305.         public int height()
  306.         {
  307.             return height(root);
  308.         }
  309.        
  310.         //helper method for height
  311.         private int height(TreeNode<E> root)
  312.         {
  313.             if(root ==null)
  314.             {
  315.                 return 0;
  316.             }
  317.             else
  318.             {
  319.                 return 1 + Math.max(height(root.left),height(root.right));
  320.             }
  321.         }
  322.     }
  323.    
  324.     /** Obtain an iterator. Use inorder. */
  325.     public java.util.Iterator<E> iterator() {
  326.         return new InorderIterator();
  327.     }
  328.  
  329.     // Inner class InorderIterator
  330.     private class InorderIterator implements java.util.Iterator<E> {
  331.         // Store the elements in a list
  332.         private java.util.ArrayList<E> list = new java.util.ArrayList<E>();
  333.         private int current = 0; // Point to the current element in list
  334.  
  335.         public InorderIterator() {
  336.             inorder(); // Traverse binary tree and store elements in list
  337.         }
  338.  
  339.         /** Inorder traversal from the root */
  340.         private void inorder() {
  341.             inorder(root);
  342.         }
  343.  
  344.         /** Inorder traversal from a subtree */
  345.         private void inorder(TreeNode<E> root) {
  346.             if (root == null)
  347.                 return;
  348.             inorder(root.left);
  349.             list.add(root.element);
  350.             inorder(root.right);
  351.         }
  352.  
  353.         /** More elements for traversing? */
  354.         public boolean hasNext() {
  355.             if (current < list.size())
  356.                 return true;
  357.  
  358.             return false;
  359.         }
  360.  
  361.         /** Get the current element and move to the next */
  362.         public E next() {
  363.             return list.get(current++);
  364.         }
  365.  
  366.         /** Remove the current element */
  367.         public void remove() {
  368.             delete(list.get(current)); // Delete the current element
  369.             list.clear(); // Clear the list
  370.             inorder(); // Rebuild the list
  371.         }
  372.     }
  373.  
  374.     /** Remove all elements from the tree */
  375.     public void clear() {
  376.         root = null;
  377.         size = 0;
  378.     }
  379. }
  380.  
  381.  
  382. //////////////////////////////////////////////////////////
  383.  
  384. public abstract class AbstractTree<E extends Comparable<E>>
  385. implements Tree<E>
  386. {
  387. //Inorder traversal from the root
  388. public void inorder(){}
  389.  
  390. //Postorder traversal from the root
  391. public void postorder(){}
  392.  
  393. //Preorder traversal from the root
  394. public void preorder(){}
  395.  
  396. //Check if tree empty
  397. public boolean isEmpty()
  398. {
  399.     return getSize() ==0;
  400. }
  401.  
  402. //Retrun an interator to traverse elements in the tree
  403. public java.util.Iterator<E> iterator()
  404. {
  405.     return null;
  406. }
  407.  
  408. }
  409.  
  410. ////////////////////////////////////////////////////////////////////////////////////////////////////
  411.  
  412. public interface Tree<E extends Comparable<E>>
  413. {
  414. //return true if the element is in the tree
  415. public boolean search(E e);
  416.  
  417. //Insert element e into the binary tree
  418. public boolean insert (E e);
  419.  
  420. //Delete the specified element from tree
  421. public boolean delete(E e);
  422.  
  423. //Inorder traversal
  424. public void inorder();
  425.  
  426. //Postorder traversal
  427. public void postorder();
  428.  
  429. //Preorder traversal
  430. public void preorder();
  431.  
  432. //get number of nodes
  433. public int getSize();
  434.  
  435. //return true if tree empty
  436. public boolean isEmpty();
  437.  
  438. //Return iterator to traverse elements
  439. public java.util.Iterator<E> iterator();
  440. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement