Binary Search Tree - Java Snippets _ Dream.in

8
3/18/2015 Binary Search Tree Java Snippets | Dream.In.Code http://www.dreamincode.net/forums/topic/364061BinarySearchTree/ 1/8 view source print ? 001 /** 002 * BST.java 003 * 004 * An unbalanced node‐based binary search tree. On average, operations are O(log(n)). 005 * Removing nodes can quickly linearize the tree so that some operations become O(n). 006 * For O(log(n)) operations in the worst case, use AVL or Red‐Black Trees: {@link http://en.wikipedia.org/wiki/AVL%20tree }. 007 * Inserting, removing, and searching rely on Comparable.CompareTo. 008 * 009 * @author Ryan Beckett 010 * @version 1.0 011 * JDK 1.7 012 * 10/16/2011 013 * 014 */ 015 public class BST<T extends Comparable<? super T>> { 016 017 private Node<T> treeRoot; 018 019 /** 020 * Insert a value into the tree. 021 */ 022 public void insert(T val) { 023 if(treeRoot == null) { 024 treeRoot = new Node<T>(val); 025 }else { 026 insert(treeRoot, val); 027 } 028 } 029 030 private void insert(Node<T> root, T val) { 031 if(val.compareTo(root.val) <= 0) { 032 if(root.left == null) { //insert as left child 033 root.left = new Node<T>(val); 034 }else { //traverse left subtree 035 insert(root.left, val); 036 } 037 }else if(val.compareTo(root.val) > 0) { 038 if(root.right == null) { //insert as right child 039 root.right = new Node<T>(val); 040 }else { //traverse right subtree 041 insert(root.right, val); 042 }

description

BST

Transcript of Binary Search Tree - Java Snippets _ Dream.in

  • 3/18/2015 BinarySearchTreeJavaSnippets|Dream.In.Code

    http://www.dreamincode.net/forums/topic/364061BinarySearchTree/ 1/8

    viewsource

    print?001 /**

    002 *BST.java

    003 *

    004 *Anunbalancednodebasedbinarysearchtree.Onaverage,operationsareO(log(n)).

    005 *RemovingnodescanquicklylinearizethetreesothatsomeoperationsbecomeO(n).

    006 *ForO(log(n))operationsintheworstcase,useAVLorRedBlackTrees:{@linkhttp://en.wikipedia.org/wiki/AVL%20tree}.

    007 *Inserting,removing,andsearchingrelyonComparable.CompareTo.

    008 *

    009 *@authorRyanBeckett

    010 *@version1.0

    011 *JDK1.7

    012 *10/16/2011

    013 *

    014 */

    015 publicclassBST

  • 3/18/2015 BinarySearchTreeJavaSnippets|Dream.In.Code

    http://www.dreamincode.net/forums/topic/364061BinarySearchTree/ 2/8

    043 }

    044 }

    045 046 privatevoidinsert(Nodend){

    047 if(nd==null)return;

    048 if(treeRoot==null){//createtreeroot

    049 treeRoot=nd;

    050 }else{//insertintotree051 insert(treeRoot,nd);

    052 }

    053 }

    054 055 privatevoidinsert(Noderoot,Nodend){

    056 if(nd.val.compareTo(root.val)0){063 if(root.right==null){//insertasrightchild

    064 root.right=nd;

    065 }else{//traverserightsubtree066 insert(root.right,nd);

    067 }

    068 }

    069 }

    070 071 /**

    072 *Searchforavalueinthetree.073 */

    074 publicNodesearch(Tval){

    075 returnsearch(treeRoot,val);076 }

    077 078 privateNodesearch(Noderoot,Tval){

    079 if(root==null)returnnull;080 if(val.compareTo(root.val)0)//traverserightsubtree083 returnsearch(root.right,val);084 else//foundtarget085 returnroot;086 }

  • 3/18/2015 BinarySearchTreeJavaSnippets|Dream.In.Code

    http://www.dreamincode.net/forums/topic/364061BinarySearchTree/ 3/8

    087 088 /**

    089 *Performaninordertreetraversal.Displaythetreeelementsinascendingorder.

    090 */

    091 publicvoidprint(){

    092 System.out.print("Tree:");

    093 if(treeRoot==null){

    094 System.out.println();

    095 return;

    096 }

    097 print(treeRoot);

    098 System.out.println();

    099 }

    100 101 privatevoidprint(Noderoot){

    102 if(root.left!=null)//traverseleftsubtreefirst

    103 print(root.left);

    104 System.out.print(root+",");//nowvisitthenode105 if(root.right!=null)

    106 print(root.right);//traverserightsubtreeafter

    107 }

    108 109 /**

    110 *Removeavaluefromthetreeandreturnitsnode.111 */

    112 publicNoderemove(Tval){

    113 returnremove(treeRoot,treeRoot,val);114 }

    115 116 privateNoderemove(Noderoot,Nodeparent,Tval){

    117 if(root==null)returnnull;//endoftree;targetnotfound118 if(val.compareTo(root.val)0){//traverserightsubtree121 returnremove(root.right,root,val);122 }else{//foundnode;linkroot'sparenttooneofroot'schildren123 adjust(root,parent);

    124 returnroot;125 }

    126 }

    127 128 /**

    129 *Removenodebylettingoneofitschildrentakeitsplace.

    130 */

  • 3/18/2015 BinarySearchTreeJavaSnippets|Dream.In.Code

    http://www.dreamincode.net/forums/topic/364061BinarySearchTree/ 4/8

    131 privatevoidadjust(Noderoot,Nodeparent){

    132 //We'reremovingaleaf

    133 if(root.left==null&&root.right==null){

    134 if(root==treeRoot){//We'reremovingtherootoftree,justclearthetree.

    135 treeRoot=null;

    136 }elseif(root.val.compareTo(parent.val)

  • 3/18/2015 BinarySearchTreeJavaSnippets|Dream.In.Code

    http://www.dreamincode.net/forums/topic/364061BinarySearchTree/ 5/8

    parent.left=root.right;

    171 }else{//itisitsparent'srightchild172 parent.right=root.right;

    173 }

    174 }

    175 }

    176 }

    177 }

    178 179 /**

    180 *Clearthetree.

    181 */

    182 publicvoidclear(){

    183 treeRoot=null;

    184 }

    185 186 /*TestDriver*/

    187 publicstaticvoidmain(Stringargs[]){

    188 189 ///////////////////

    190 //Integerexample

    191 ///////////////////

    192 System.out.println("nIntegerlistexamplen");

    193 BSTt=newBST();

    194 195 ///////////////////

    196 //Inserting

    197 ///////////////////

    198 t.insert(5);

    199 t.insert(2);

    200 t.insert(7);

    201 t.insert(1);

    202 t.insert(5);

    203 t.insert(3);

    204 t.insert(6);

    205 t.insert(10);

    206 t.insert(3);

    207 t.print();

    208 209 ///////////////////

    210 //Searching

    211 ///////////////////

    212 inttarget=10;

    213 if(t.search(target)!=null)

    214 {

  • 3/18/2015 BinarySearchTreeJavaSnippets|Dream.In.Code

    http://www.dreamincode.net/forums/topic/364061BinarySearchTree/ 6/8

    215 System.out.println(target+"wasfound");

    216 }else{217 System.out.println(target+"wasnotfound");

    218 }

    219 target=0;

    220 if(t.search(target)!=null)

    221 {

    222 System.out.println(target+"wasfound");

    223 }else{224 System.out.println(target+"wasnotfound");

    225 }

    226 target=2;

    227 if(t.search(target)!=null)

    228 {

    229 System.out.println(target+"wasfound");

    230 }else{231 System.out.println(target+"wasnotfound");

    232 }

    233 234 ///////////////////

    235 //Removing

    236 ///////////////////

    237 System.out.println("Removing11");

    238 t.remove(11);

    239 t.print();

    240 System.out.println("Removing5");

    241 t.remove(5);

    242 t.print();

    243 System.out.println("Removing1");

    244 t.remove(1);

    245 t.print();

    246 System.out.println("Removing6");

    247 t.remove(6);

    248 t.print();

    249 System.out.println("Removing10");

    250 t.remove(10);

    251 t.print();

    252 System.out.println("Removing3");

    253 t.remove(3);

    254 t.print();

    255 System.out.println("Removing3");

    256 t.remove(3);

    257 t.print();

    258 259

  • 3/18/2015 BinarySearchTreeJavaSnippets|Dream.In.Code

    http://www.dreamincode.net/forums/topic/364061BinarySearchTree/ 7/8

    260 ///////////////////

    261 //Stringexample

    262 ///////////////////

    263 System.out.println("nnStringlistexamplen");

    264 BSTs=newBST();

    265 266 ///////////////////

    267 //Inserting

    268 ///////////////////

    269 s.insert("foo");270 s.insert("?>}|");

    271 s.insert("bar");272 s.insert("qux");273 s.insert("baz");274 s.insert("?>");

    275 s.insert("qux");276 s.print();

    277 278 ///////////////////

    279 //Searching

    280 ///////////////////

    281 StringstrTarget="?>}";

    282 if(s.search(strTarget)!=null)

    283 {

    284 System.out.println(strTarget+"wasfound");

    285 }else{286 System.out.println(strTarget+"wasnotfound");

    287 }

    288 strTarget="bar";

    289 if(s.search(strTarget)!=null)

    290 {

    291 System.out.println(strTarget+"wasfound");

    292 }else{293 System.out.println(strTarget+"wasnotfound");

    294 }

    295 296 ///////////////////

    297 //Removing

    298 ///////////////////

    299 System.out.println("Removingbar");

    300 s.remove("bar");301 s.print();

    302 System.out.println("Removingbaz");

    303 s.remove("baz");

  • 3/18/2015 BinarySearchTreeJavaSnippets|Dream.In.Code

    http://www.dreamincode.net/forums/topic/364061BinarySearchTree/ 8/8

    304 s.print();

    305 System.out.println("Removingqux");

    306 s.remove("qux");307 s.print();

    308 System.out.println("Removing?>}|");

    309 s.remove("?>}|");310 s.print();

    311 System.out.println("Removing?>}|");

    312 s.remove("?>}|");313 s.print();

    314 }

    315 }

    316 317 classNode