2011-03-19 61 views
0

我已經構建了一棵樹來保存每條記錄的單個字符串(數據)。我怎樣才能讓它爲每個記錄保存多個字符串?每個樹記錄的多個值

void BinarySearchTree::insert(string d) 
{ 
tree_node* t = new tree_node; 
tree_node* parent; 
t->data = d; 
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 > curr->data) curr = curr->right; 
     else curr = curr->left; 
    } 

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

回答

0

每個節點都有多個指針。這些指針將指向一個字符串數據。這些指針可能是動態的或根據您的需要進行修復。

0

使用標準庫的平衡二叉樹(std :: set,multiset,map,multimap)。使用一串字符串作爲密鑰,如

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

您可以在記錄中添加一個數組或字符串向量。你必須有一個關鍵字符串來比較你的樹的節點。使用字符串數組/矢量

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

的第一個元素插入

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; 
     } 
    } 
    } 

現在你可以 1.Insert一個新的字符串轉換成基於關鍵字的現有節點。 2.僅通過提供new_string,用新關鍵字創建新節點。 3.讓一個新節點同時插入關鍵字和另一個字符串。

不知道這是不是你想要的東西我不是一個真正的C++程序員,所以這可能是錯誤的代碼...