Advertisement
Guest User

Untitled

a guest
Apr 15th, 2014
53
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 13.59 KB | None | 0 0
  1. import java.util.ArrayList;
  2. import java.util.Collection;
  3. import java.util.Iterator;
  4. import java.util.LinkedList;
  5. import java.util.TreeSet;
  6. import sun.misc.Queue;
  7.  
  8. /**
  9. * Binary Search Tree that inherits from the TreeSet class
  10. * The class is based on Weiss's non-generic implementation of BinarySearchTree
  11. *
  12. * @author Daniel
  13. * @param <T>
  14. */
  15. public class BinarySearchTree<T extends Comparable<T>> extends TreeSet<T> implements Iterable<T>
  16. {
  17. /**
  18. * Construct the tree.
  19. */
  20. public BinarySearchTree( )
  21. {
  22. root = null;
  23. }
  24.  
  25. @Override
  26. public boolean add(T e)
  27. {
  28. insert(e);
  29. return true;
  30. }
  31.  
  32.  
  33.  
  34. /**
  35. * Insert into the tree; duplicates are ignored.
  36. * @param x the item to insert.
  37. */
  38. public void insert( Comparable x )
  39. {
  40. {
  41.  
  42. root = insert( x, root );
  43.  
  44. }
  45.  
  46. }
  47.  
  48. /**
  49. * Remove from the tree. Nothing is done if x is not found.
  50. * @param x the item to remove.
  51. */
  52. public void remove( Comparable<T> x )
  53. {
  54.  
  55. root = remove( x, root );
  56.  
  57.  
  58. }
  59.  
  60. /**
  61. * Find the smallest item in the tree.
  62. * @return smallest item or null if empty.
  63. */
  64. public Comparable findMin( )
  65. {
  66. return elementAt( findMin( root ) );
  67. }
  68.  
  69. /**
  70. * Find the largest item in the tree.
  71. * @return the largest item of null if empty.
  72. */
  73. public Comparable findMax( )
  74. {
  75. return elementAt( findMax( root ) );
  76. }
  77.  
  78. /**
  79. * Find an item in the tree.
  80. * @param x the item to search for.
  81. * @return the matching item or null if not found.
  82. */
  83. public Comparable find( Comparable x )
  84. {
  85. return elementAt( find( x, root ) );
  86. }
  87.  
  88. /**
  89. * Make the tree logically empty.
  90. */
  91. public void makeEmpty( )
  92. {
  93. root = null;
  94. }
  95.  
  96. /**
  97. * Test if the tree is logically empty.
  98. * @return true if empty, false otherwise.
  99. */
  100. public boolean isEmpty( )
  101. {
  102. return root == null;
  103. }
  104.  
  105. /**
  106. * Print the tree contents in sorted order.
  107. */
  108. public void printTree( )
  109. {
  110. if( isEmpty( ) )
  111. System.out.println( "Empty tree" );
  112. else
  113. printTree( root );
  114. }
  115.  
  116. /**
  117. * Internal method to get element field.
  118. * @param t the node.
  119. * @return the element field or null if t is null.
  120. */
  121. private Comparable elementAt( BinaryNode t )
  122. {
  123. return t == null ? null : t.element;
  124. }
  125.  
  126. /**
  127. * Internal method to insert into a subtree.
  128. * @param x the item to insert.
  129. * @param t the node that roots the tree.
  130. * @return the new root.
  131. */
  132. private BinaryNode insert( Comparable<T> x, BinaryNode<T> t )
  133. {
  134. /* 1*/ if( t == null )
  135. {
  136. /* 2*/ t = new BinaryNode( x, null, null );
  137.  
  138. t.parent = null;
  139. if (t.left != null)
  140. t.left.parent = t;
  141. if (t.right != null)
  142. t.right.parent = t;
  143. }
  144. /* 3*/ else if( x.compareTo((T)t.element ) < 0 )
  145. {
  146. /* 4*/ t.left = insert( x, t.left );
  147. t.left_count++;
  148. t.left.parent = t;
  149.  
  150. }
  151. /* 5*/ else if( x.compareTo((T) t.element ) > 0 )
  152. {
  153. /* 6*/ t.right = insert( x, t.right );
  154. t.right.parent = t;
  155.  
  156. }
  157. /* 7*/ else
  158. /* 8*/ ; // Duplicate; do nothing
  159. /* 9*/ return t;
  160. }
  161.  
  162. /**
  163. * Internal method to remove from a subtree.
  164. * @param x the item to remove.
  165. * @param t the node that roots the tree.
  166. * @return the new root.
  167. */
  168. private BinaryNode remove( Comparable<T> x, BinaryNode<T> t )
  169. {
  170. if( t == null )
  171. return t; // Item not found; do nothing
  172. if( x.compareTo( (T)t.element ) < 0 )
  173. {
  174. t.left = remove( x, t.left );
  175.  
  176. }
  177. else if( x.compareTo( (T)t.element ) > 0 )
  178. {
  179. t.right = remove( x, t.right );
  180.  
  181.  
  182. }
  183. else if( t.left != null && t.right != null ) // Two children
  184. {
  185. t.element = findMin( t.right ).element;
  186. t.right = remove( t.element, t.right );
  187.  
  188.  
  189. }
  190. else
  191. t = ( t.left != null ) ? t.left : t.right;
  192. if (t != null)
  193. {
  194. if (t.left != null)
  195. t.left.parent = t;
  196. if (t.right != null)
  197. t.right.parent = t;
  198. }
  199. return t;
  200. }
  201.  
  202. /**
  203. * Internal method to find the smallest item in a subtree.
  204. * @param t the node that roots the tree.
  205. * @return node containing the smallest item.
  206. */
  207. private BinaryNode<T> findMin( BinaryNode<T> t )
  208. {
  209. if( t == null )
  210. return null;
  211. else if( t.left == null )
  212. return t;
  213. return findMin( t.left );
  214. }
  215.  
  216. /**
  217. * Internal method to find the largest item in a subtree.
  218. * @param t the node that roots the tree.
  219. * @return node containing the largest item.
  220. */
  221. private BinaryNode<T> findMax( BinaryNode<T> t )
  222. {
  223. if( t != null )
  224. while( t.right != null )
  225. t = t.right;
  226.  
  227. return t;
  228. }
  229.  
  230. /**
  231. * Internal method to find an item in a subtree.
  232. * @param x is item to search for.
  233. * @param t the node that roots the tree.
  234. * @return node containing the matched item.
  235. */
  236. private BinaryNode find( Comparable<T> x, BinaryNode<T> t )
  237. {
  238. if( t == null )
  239. return null;
  240. if( x.compareTo( (T)t.element ) < 0 )
  241. return find( x, t.left );
  242. else if( x.compareTo( (T)t.element ) > 0 )
  243. return find( x, t.right );
  244. else
  245. return t; // Match
  246. }
  247.  
  248. /**
  249. * Internal method to print a subtree in sorted order.
  250. * @param t the node that roots the tree.
  251. */
  252. private void printTree( BinaryNode<T> t )
  253. {
  254. if( t != null )
  255. {
  256. printTree( t.left );
  257. System.out.println( t.element );
  258. printTree( t.right );
  259. }
  260. }
  261.  
  262.  
  263. @Deprecated
  264. //Updates nodes current parent
  265. // Unfortunaetly to expensive as it is O(N) algorithm.
  266. // Therefore it sadly didn't make the final cut and is a deprecated method can be removed in the near future.
  267. private void update(BinaryNode<T> t)
  268. {
  269. if (t != null)
  270. {
  271. if (t.left != null)
  272. t.left.parent = t;
  273. if (t.right != null)
  274. t.right.parent = t;
  275. update(t.left);
  276. update(t.right);
  277. }
  278. }
  279.  
  280.  
  281. /**
  282. * Returns an iterator pointing just before the
  283. * item in the tree with the lowest value.
  284. *
  285. **/
  286.  
  287. public Iterator<T> iterator()
  288. {
  289. return new MyIterator();
  290. }
  291.  
  292.  
  293. /**
  294. * Returns the element at a given index position.
  295. * Throws an IndexOutOfBoundsException if the item is not found.
  296. * Runs in average O(log N) time.
  297. */
  298. public T get( int index )
  299. {
  300. return get(root, index);
  301. }
  302.  
  303. private T get(BinaryNode<T> root, int index)
  304. {
  305. if (root == null) return null;
  306. if (root.left_count == index-1) return (T)root.element;
  307. if (root.left_count < index) return get(root.right, index - (root.left_count + 1));
  308. else
  309. {
  310. return get(root.left, index);
  311. }
  312. }
  313.  
  314.  
  315. /**
  316. * Returns all elements falling within a range of indexes.
  317. * The range is inclusive
  318. */
  319.  
  320. public Collection<T> getRange( int first, int last )
  321. {
  322. ArrayList<T> list = new ArrayList<>();
  323. for(int i = first; i <= last; i++)
  324. {
  325. list.add(get(i));
  326. }
  327. return list;
  328. }
  329.  
  330. /**
  331. * Prints the tree in level-order, which means the root is printed,
  332. * then all nodes at level 2, then nodes at level 3, and so on.
  333. */
  334. public void printLevelOrder( ) throws InterruptedException
  335. {
  336. Queue Q = new Queue();
  337. Q.enqueue(root);
  338. while(!Q.isEmpty())
  339. {
  340. BinaryNode<T> node = (BinaryNode<T>)Q.dequeue();
  341. System.out.print(node.element + ",");
  342. if (node.left != null)
  343. Q.enqueue(node.left);
  344. if (node.right != null)
  345. Q.enqueue(node.right);
  346. }
  347. System.out.println();
  348. }
  349.  
  350.  
  351.  
  352.  
  353.  
  354.  
  355. private class MyIterator implements Iterator<T>
  356. {
  357.  
  358. private BinaryNode<T> nextNode = null;
  359. private boolean firstCall;
  360. public MyIterator()
  361. {
  362. nextNode = BinarySearchTree.this.findMin(root);
  363. firstCall = true;
  364. }
  365. @Override
  366. public boolean hasNext()
  367. {
  368. return !nextNode.equals(BinarySearchTree.this.findMax(root));
  369. }
  370.  
  371. @Override
  372. public T next()
  373. {
  374. if (firstCall)
  375. {
  376. firstCall = false;
  377. return (T)nextNode.element;
  378. }
  379. if (!hasNext())
  380. throw new IndexOutOfBoundsException("Cannot manke another next() call!!!!?!");
  381. BinaryNode<T> node = successor(nextNode);
  382. nextNode = node;
  383. return (T)node.element;
  384. }
  385.  
  386. @Override
  387. public void remove()
  388. {
  389. BinarySearchTree.this.remove(nextNode.element);
  390. }
  391.  
  392. /**
  393. * Returns the next value in the sequence, starting at the
  394. * node pointed to by the input parameter. This method
  395. * is used by the iterator.
  396. */
  397. private BinaryNode<T> successor( BinaryNode<T> p )
  398. {
  399. BinaryNode<T> n = p.right;
  400. if (n != null)
  401. {
  402. return BinarySearchTree.this.findMin(n);
  403. }
  404. else
  405. {
  406. n = p.parent;
  407. while(n != null && p == n.right)
  408. {
  409. p = n;
  410. n = n.parent;
  411. }
  412. return n;
  413. }
  414. }
  415.  
  416.  
  417. }
  418.  
  419.  
  420.  
  421. /** The tree root. */
  422. private BinaryNode<T> root;
  423.  
  424.  
  425.  
  426. public static void main(String[] arguments) throws InterruptedException
  427. {
  428.  
  429. BinarySearchTree<String> t = new BinarySearchTree<>();
  430. String[] array = { "Harry","Maria","Bob","Dan","Sue","Ann","Jose" };
  431.  
  432. for(int i = 0; i < array.length; i++)
  433. t.insert(array[i]);
  434. print( t );
  435.  
  436. System.out.print("Level order: ");
  437. t.printLevelOrder();
  438. System.out.println("n");
  439.  
  440. System.out.printf( "The value at index %d is %sn", 0, t.get(0) );
  441. System.out.printf( "The value at index %d is %sn", 2, t.get(2) );
  442. System.out.printf( "The value at index %d is %sn", 6, t.get(6) );
  443.  
  444. System.out.print("nRemoving ");
  445. for( int i = 1; i < array.length; i+= 2 ) {
  446. System.out.print(array[i] + ", ");
  447. t.remove( array[i] );
  448. }
  449. System.out.println();
  450.  
  451. System.out.println("nTree contents after removing elements:");
  452. print( t );
  453.  
  454. // verify that the get method still works
  455. System.out.printf( "The value at index %d is %sn", 0, t.get(0) );
  456. System.out.printf( "The value at index %d is %sn", 2, t.get(2) );
  457. System.out.printf( "The value at index %d is %sn", 3, t.get(3) );
  458.  
  459.  
  460. }
  461.  
  462. public static void print( BinarySearchTree<? extends Comparable<?>> t )
  463. {
  464.  
  465. for(Object x : t)
  466. System.out.print(x + ", ");
  467. System.out.println("n");
  468. }
  469.  
  470. private static void test1() throws InterruptedException
  471. {
  472. BinarySearchTree<Integer> t = new BinarySearchTree<>( );
  473. int[] array = { 20, 10, 11, 30, 2, 29, 33, 28, 17, 4 };
  474. for(int i = 0; i < array.length; i++)
  475. t.add(array[i]);
  476.  
  477. print( t ); // demonstrate the iterator
  478.  
  479. System.out.println("Level order");
  480. t.printLevelOrder();
  481.  
  482. System.out.printf( "The value at index %d is %dn", 0, t.get(0) );
  483. System.out.printf( "The value at index %d is %dn", 1, t.get(1) );
  484. System.out.printf( "The value at index %d is %dn", 2, t.get(2) );
  485. System.out.printf( "The value at index %d is %dn", 3, t.get(3) );
  486. System.out.printf( "The value at index %d is %dn", 8, t.get(8) );
  487. System.out.printf( "The value at index %d is %dn", 9, t.get(9) );
  488.  
  489. System.out.print("nRemoving ");
  490. for( int i = 1; i < array.length; i+= 2 ) {
  491. System.out.print(array[i] + ", ");
  492. t.remove( array[i] );
  493. }
  494. System.out.println();
  495.  
  496. System.out.println("nTree contents after removing elements:");
  497. print( t );
  498.  
  499. // verify that the get method still works
  500. System.out.printf( "The value at index %d is %dn", 0, t.get(0) );
  501. System.out.printf( "The value at index %d is %dn", 1, t.get(1) );
  502. System.out.printf( "The value at index %d is %dn", 2, t.get(2) );
  503. System.out.printf( "The value at index %d is %dn", 3, t.get(3) );
  504. }
  505.  
  506.  
  507.  
  508.  
  509. }
  510.  
  511. /**
  512. * Returns the element at a given index position.
  513. * Throws an IndexOutOfBoundsException if the item is not found.
  514. * Runs in average O(log N) time.
  515. */
  516. public T get( int index )
  517. {
  518. return get(root, index);
  519. }
  520.  
  521. private T get(BinaryNode<T> root, int index)
  522. {
  523. if (root == null) return null;
  524. if (root.left_count == index-1) return (T)root.element;
  525. if (root.left_count < index) return get(root.right, index - (root.left_count + 1));
  526. else
  527. {
  528. return get(root.left, index);
  529. }
  530. }
  531.  
  532. Ann, Bob, Dan, Harry, Jose, Maria, Sue,
  533.  
  534. Level order: Harry,Bob,Maria,Ann,Dan,Jose,Sue,
  535.  
  536.  
  537. The value at index 0 is Ann
  538. The value at index 2 is Dan
  539. The value at index 6 is Sue
  540.  
  541. Removing Maria, Dan, Ann,
  542.  
  543. Tree contents after removing elements:
  544. Bob, Harry, Jose, Sue,
  545.  
  546. The value at index 0 is null
  547. The value at index 2 is null
  548. The value at index 3 is Harry
  549.  
  550. if (root.left_count == index-1) return (T)root.element;
  551.  
  552. if (root.left_count == index) return (T)root.element;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement