Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class BinaryTree(V)
- {
- alias RB_Node!V Node;
- Node* root;
- int _length;
- @property empty() const { return root is null; }
- @property length() const { return _length; }
- /*
- * I don kno :<
- */
- void add( V value )
- {
- Node** ptr = &root;
- Node* cur = root;
- while( cur !is null )
- {
- /**/ if( value < cur.value ) ptr = &cur.left;
- else if( value > cur.value ) ptr = &cur.right;
- else break;
- cur = *ptr;
- }
- if( cur !is null )
- {
- // TODO Duplicate
- return;
- }
- auto child = new Node();
- child.parent = cur;
- child.value = value;
- // Finally attach to the parent
- *ptr = child;
- }
- void printme()
- {
- import shd.output;
- Node* p;
- void loop( const Node* p )
- {
- if( p.left !is null ) loop( p.left );
- Shdout.print( p.value, ", " );
- if( p.right !is null ) loop( p.right );
- }
- Shdout.print("[ ");
- loop( root );
- Shdout.println("]");
- }
- }
- void main()
- {
- auto tree = new BinaryTree!int;
- foreach( i; [ 1, 4, 8, 10, 3, 7, 20 ] )
- tree.add( i );
- tree.printme;
- }
- // Output [ 1, 3, 4, 7, 8, 10, 20, ]
Advertisement
Add Comment
Please, Sign In to add comment