开发者

Multiple values for each tree record

I have constructed a tree to hold a single string(data) for each record. How can I make it hold multiple strings for each record?

void BinarySearchTree::insert(string d)
{
tree_node* t = new tree_node;
tree_node* parent;
t->data = d;
t->left = NULL;
开发者_JAVA百科t->right = NULL;
parent = NULL;

// is this a new tree?
if(isEmpty()) root = t;
else
{
    //Note: ALL insertions are as leaf nodes
    tree_node* curr;
    curr = root;
    // Find the Node's parent
    while(curr)
    {
        parent = curr;
        if(t->data > curr->data) curr = curr->right;
        else curr = curr->left;
    }

    if(t->data < parent->data)
       parent->left = t;
    else
       parent->right = t;
   }
  }


Have multiple pointers for each node. Those pointers will point to a string-data. Those pointers may be dynamic or fixed depending on your need.


Use the standard library's balanced binary trees (std::set, multiset, map, multimap). Use a vector of strings as the key, like

std::set<std::vector<std::string> >


You can just have an array or vector of strings in the record. You have to have a key string to compare the nodes by for your tree. Use the first element of the string array/vector

struct t {
  //other fields...
  std::vector<std::string> data;
};

On insert

void BinarySearchTree::insert(string new_string, string key_string)
    {
    if(!key_string.empty()) 
    {  
      BinarySearchTree::tree_node *existing_node = BinarySearchTree::find( key_string );
      if(existing_node)
      {
        existing_node->data.push_back(new_string);
      }
    }     
    else 
    {
      tree_node* t = new tree_node;
      tree_node* parent;
      if(!key_string.empty())
        t->data.push_back(key_string);
      if(!new_string.empty())          
        t->data.push_back(new_string);
      t->left = NULL;
      t->right = NULL;
      parent = NULL;

      // is this a new tree?
      if(isEmpty()) root = t;
      else
      {
        //Note: ALL insertions are as leaf nodes
        tree_node* curr;
        curr = root;
        // Find the Node's parent
        while(curr)
        {
            parent = curr;
            if(t->data[0] > curr->data[0]) curr = curr->right;
            else curr = curr->left;
        }

        if(t->data[0] < parent->data[0])
           parent->left = t;
        else
           parent->right = t;
      }
    }
  }

now you can 1.Insert a new string into an existing node based on keyword. 2.Make a new node with a new keyword by only supplying new_string. 3.Make a new node inserting both keyword and another string at the same time.

Not sure if this is something like you're looking for or not I'm not a real c++ programmer so there may very well be errors in this code...

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜