C++ print out a binary search tree

Posted by starcorn on Stack Overflow See other posts from Stack Overflow or by starcorn
Published on 2010-12-27T22:41:36Z Indexed on 2010/12/27 22:54 UTC
Read the original article Hit count: 384

Filed under:
|
|

Hello, Got nothing better to do this Christmas holiday, so I decided to try out making a binary search tree. I'm stuck with the print function. How should the logic behind it work? Since the tree is already inserting it in a somewhat sorted order, and I want to print the tree from smallest values to the biggest.

So I need to travel to the furthest left branch of the tree to print the first value. Right, so after that how do I remember the way back up, do I need to save the previous node? A search in wikipedia gave me an solution which they used stack. And other solutions I couldn't quite understand how they've made it, so I'm asking here instead hoping someone can enlight me.

I also wonder my insert function is OK. I've seen other's solution being smaller.

void treenode::insert(int i)
{

   if(root == 0)
   {
      cout << "root" << endl;
      root = new node(i,root);
   }
   else
   {
      node* travel = root;
      node* prev;
      while(travel)
      {
         if(travel->value > i)
         {
            cout << "travel left" << endl;
            prev = travel;
            travel = travel->left;
         }
         else
         {
            cout << "travel right" << endl;
            prev = travel;
            travel = travel->right;
         }
      }
      //insert
      if(prev->value > i)
      {
         cout << "left" << endl;
         prev->left = new node(i);
      }
      else
      {
         cout << "right" << endl;
         prev->right = new node(i);
      }
   }

}

void treenode::print()
{

   node* travel = root;
   while(travel)
   {
      cout << travel->value << endl;
      travel = travel->left;
   }

}

© Stack Overflow or respective owner

Related posts about c++

Related posts about binary-trees