DataStructureNote

=List=

=Stack=
 * LIFO, Insert and remove from only one end, last in first out.

=Queue=
 * FIFO,enqueue at back, dequeue from the front, first in first out.

=Dictionary=
 * Dictionary is (obsolete by) Map.

=Binary Tree=

Binary Tree Traversals

 * preorder visit any given node before we visit its children
 * inorder visits the left child then visits the node, finally visits the right child
 * postorder visit each node only after we visit its children

Find Min and Max
1 /** 2 * Internal method to find the smallest item in a subtree. 3 * @param t the node that roots the subtree. 4 * @return node containing the smallest item. 5 */ 6 private BinaryNode findMin( BinaryNode t ) 7 { 8 if( t == null ) 9 return null; 10 else if( t.left == null ) 11 return t; 12 return findMin( t.left ); 13 } 14 15 /** 16 * Internal method to find the largest item in a subtree. 17 * @param t the node that roots the subtree. 18 * @return node containing the largest item. 19 */ 20 private BinaryNode findMax( BinaryNode t ) 21 { 22 if( t != null ) 23 while( t.right != null ) 24 t = t.right; 25 26 return t; 27 }

Insert
1 /** 2 * Internal method to insert into a subtree. 3 * @param x the item to insert. 4 * @param t the node that roots the subtree. 5 * @return the new root of the subtree. 6 */ 7 private BinaryNode insert( AnyType x, BinaryNode t ) 8 { 9 if( t == null ) 10 return new BinaryNode<>( x, null, null ); 11 12 int compareResult = x.compareTo( t.element ); 13 14 if( compareResult < 0 ) 15 t.left = insert( x, t.left ); 16 else if( compareResult > 0 ) 17 t.right = insert( x, t.right ); 18 else 19 ; // Duplicate; do nothing 20 return t; 21 }

Remove
1 /** 2 * Internal method to remove from a subtree. 3 * @param x the item to remove. 4 * @param t the node that roots the subtree. 5 * @return the new root of the subtree. 6 */ 7 private BinaryNode remove( AnyType x, BinaryNode t ) 8 { 9 if( t == null ) 10 return t; // Item not found; do nothing 11 12 int compareResult = x.compareTo( t.element ); 13 14 if( compareResult < 0 ) 15 t.left = remove( x, t.left ); 16 else if( compareResult > 0 ) 17 t.right = remove( x, t.right ); 18 else if( t.left != null && t.right != null ) // Two children 19 { 20 t.element = findMin( t.right ).element; 21 t.right = remove( t.element, t.right ); 22 } 23 else 24 t = ( t.left != null ) ? t.left : t.right; 25 return t; 26