开发者

How can I create the tree?

I'm trying to make a BST and need to print it inorder, postorder, and preorder.

The thing am not sure about is how to create this tree in my main() function.

struct Tree_Node
{
    Tree_Node *right;
    Tree_Node *left;
    int info;
};

class bTree
{
private:
    Tree_Node *root;
public:
    bTree();
    void bTree::Insert(Tree_Node*& tree, int item);
    void bTree::preorderPrint(Tree_Node *root);
};

bTree::bTree()
{
    root = NULL;
}


void bTree::Insert(Tree_Node*& tree, int item)
{
  if (tree == NULL)
  {
    tree = new Tree_Node;
    tree->right = NULL;
    tree->left = NULL;
    tree->info = item;
  }
  else if (item < tree->info)
    Insert(tree->left, item);    
  else
    Insert(tree->right, item);   
} 

void bTree::preorderPrint(Tree_Node *root)
{
    if ( root != NULL ) 
    {
        cout << root->info << " ";
        preorderPrint( root->left );   
        preorderPrint( root->right );   
    }
}

void main()
{
// This is where I need help at
// I'm not sure how to insert开发者_如何学JAVA a new node

    bTree Test;
    Test.Insert(    
}


By the looks of things, you can just write

Test.Insert(Test.root, 3); // Insert 3
Test.Insert(Test.root, 4); // Insert 4

and that should work. Of course, you'll have to make root public.

However, this is a bit awkward, since the first parameter will always be bTree.root - and you don't need to make that public. Remember that the user of your data type (you or anyone else) shouldn't have to care about internals such as nodes - they only care about their data. Instead, I'd recommend making a convenience Insert method which only needs to take an integer (not a tree node) - this is called Overloading.

void bTree::Insert(int item)
{
    Insert(root, item);
}

// Keep the other insert method, but make it private.

Then you can just write:

Test.Insert(3);
Test.Insert(4);


void bTree::Insert(int item)
{
  Tree_Node * node = new Tree_Node;
  node->left = NULL;
  node->right = NULL;
  node->info = item;
  if (root == NULL)
  {
    root = node;
    return;
  }
  Tree_Node * t = root;
  Tree_Node * p = root;
  while(1)
  {
    if (item < t->info)
    {
       t = t->left;
       if(t == NULL)
       {
          p->left = node;
          return;
       }
    }
    else if(item > t->info)
    {
       t = t->right;
       if(t == NULL)
       {
          p->right = node;
          return;
       }
    }
    else //item already exists in the tree
       return;
    p = t;
  }

} 

//now you can insert nodes like
Test.Insert(5);
Test.Insert(6);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜