Advertisement
Guest User

BinarySearchTree.java

a guest
Nov 25th, 2014
208
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.35 KB | None | 0 0
  1. public class BinarySearchTree extends BinaryTree {
  2.  
  3.     public BinarySearchTree() {
  4.         super();
  5.     }
  6.  
  7.     public void insert(Comparable item) {
  8.         if(this.isEmpty())
  9.             this.setRoot(new TreeNode(item));
  10.  
  11.         TreeNode p = null;
  12.         TreeNode q = this.getRoot();
  13.         while(q != null) {
  14.             p = q;
  15.             if(item.compareTo(p.getValue()) < 0)
  16.                 q = p.getLeft();
  17.             else
  18.                 q = p.getRight();
  19.         }
  20.  
  21.         if(item.compareTo(p.getValue()) < 0)
  22.             p.setLeft(new TreeNode(item));
  23.         else
  24.             p.setRight(new TreeNode(item));
  25.     }
  26.  
  27.     public TreeNode find(Comparable key) {
  28.         TreeNode p = this.getRoot();
  29.         while(p != null && key.compareTo(p.getValue()) != 0) {
  30.             if(key.compareTo(p.getValue()) < 0)
  31.                 p = p.getLeft();
  32.             else
  33.                 p = p.getRight();
  34.         }
  35.         return p;
  36.     }
  37.  
  38.     // public BinarySearchTree swapSubtrees() {
  39.        
  40.     // }
  41.  
  42.     public void inorder() {
  43.         doInorderTraversal(this.getRoot());
  44.     }
  45.  
  46.     private void doInorderTraversal(TreeNode t) {
  47.         if(t != null) {
  48.             doInorderTraversal(t.getLeft());
  49.             System.out.println(t.getValue());
  50.             doInorderTraversal(t.getRight());
  51.         }
  52.     }
  53.  
  54. } // end of class
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement