Shahid4

Untitled

Jul 31st, 2012
39
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
D 1.11 KB | None | 0 0
  1. class BinaryTree(V)
  2. {
  3.     alias  RB_Node!V  Node;
  4.  
  5.     Node* root;
  6.     int  _length;
  7.  
  8.     @property empty()  const { return root is null; }
  9.     @property length() const { return _length;      }
  10.  
  11.     /*
  12.      * I don kno :<
  13.      */
  14.     void  add( V value )
  15.     {
  16.         Node** ptr = &root;
  17.         Node*  cur =  root;
  18.         while( cur !is null )
  19.         {
  20.             /**/ if( value < cur.value )  ptr = &cur.left;
  21.             else if( value > cur.value )  ptr = &cur.right;
  22.             else break;
  23.  
  24.             cur = *ptr;
  25.         }
  26.  
  27.         if( cur !is null )
  28.         {
  29.             // TODO Duplicate
  30.             return;
  31.         }
  32.  
  33.         auto child = new Node();
  34.  
  35.         child.parent = cur;
  36.         child.value  = value;
  37.  
  38.         // Finally attach to the parent
  39.         *ptr = child;
  40.     }
  41.  
  42.     void printme()
  43.     {
  44.         import shd.output;
  45.         Node* p;
  46.  
  47.         void loop( const Node* p )
  48.         {
  49.             if( p.left  !is null )  loop( p.left );
  50.             Shdout.print( p.value, ", " );
  51.             if( p.right !is null )  loop( p.right );
  52.         }
  53.         Shdout.print("[ ");
  54.         loop( root );
  55.         Shdout.println("]");
  56.     }
  57. }
  58.  
  59. void main()
  60. {
  61.  
  62.     auto tree = new BinaryTree!int;
  63.  
  64.     foreach( i; [ 1, 4, 8, 10, 3, 7, 20 ] )
  65.         tree.add( i );
  66.  
  67.     tree.printme;
  68. }
  69.  
  70. // Output [ 1, 3, 4, 7, 8, 10, 20, ]
Advertisement
Add Comment
Please, Sign In to add comment