howdy boyz n gals:
I am finally able to insert and find an item in my binary tree!! However we has a couple of small problems still. I don't think i'm inserting properly. My desired tree is as follows; based on this input file 1(2,3(10)),4(5(8),6(9),7) i wish to achieve 1 as the root (which i get based on the following code, but thats it i think) followed with 2 at the left of 1 and 4 at the right of 1. to the right of 2 i want 3 and to the left of 3 i want 10. that makes the left branch of the root. on the right i would like 5 at the left of 4 and 8 to the left of 5 and 6 to the right of 5. and 9 and seven to the left and right of 6. i'm pretty sure its my insertion method and telling 'insert' which node to insert after, and not my printtree function. here is my code for the insert and print functions, any help appreciated. thanks.
Code:
//from my main function
cout << "root: " << number << '\n';
t.insert(number);
char child;
while(in >> child)
{
switch(child)
{
case '(':in >> number;
cout << "Insert Left Subtree: " <<
number <<'\n';t.insert(number);break;
case ')':if(in >> child){
while(child != ',')
in >>child;
}
else break;
case ',':in >> number;
cout << "Insert Right Subtree: " << number <<
'\n';t.insert(number);break;
default:cout << "Unknown char\n";break;
}
}
t.printTree();
//from my class function for insert
template <class Comparable>
void BinarySearchTree<Comparable>::
insert( const Comparable & x, BinaryNode<Comparable> * & t ) const
{
if( t == NULL )
t = new BinaryNode<Comparable>( x, NULL, NULL );
else if( x < t->element )
insert( x, t->left );
else if( t->element < x )
insert( x, t->right );
else
; // Duplicate; do nothing
}
//my print function
template <class Comparable>
void BinarySearchTree<Comparable>::printTree( BinaryNode<Comparable> *t ) const
{
if( t != NULL )
{
printTree( t->left );
cout << t->element << endl;
printTree( t->right );
}
}