2011-10-11 200 views
0

我想創建一個函數,將一個關鍵結構插入到一棵樹中。該函數正確設置了根,但在用另一個鍵再次調用時不設置分支。下面是代碼:樹指針結構

tree.h中:從樹類

class tree{ 

    key *tree_root; 

public: 
    tree(); 
    //Constructor 

    void treedestroy(key *root); 
    //Tree destructor helper 

    ~tree(); 
    //Destructor 

    void insert(key* root, key *newkey, int disc); 

}; 

插入功能:

void tree::insert(key *root, key *newkey, int disc){ 
    if (root == NULL){ 
     root = newkey; 
     return; 
    } 
    if (newkey->cord[disc] <= root->cord[disc]) 
     insert(root->left, newkey, (disc+1)%4); 
    else if (newkey->cord[disc] > root->cord[disc]) 
     insert(root->right, newkey, (disc+1)%4); 
} 

我與C++的指針一點點經驗不足,不知道我怎麼能解決這個問題代碼,以便它將正確填充樹?

回答

1

我不能完全肯定這裏你的方法,但以幫助你在你的腳下,這將有助於使用的函數簽名:

void insert(key*& root, key *newkey, int disc); 

這通過傳遞根指針這意味着函數內部所做的更改將「粘」到您通過的變量中。

您的函數按原樣修改函數局部變量,但不會傳播這些更改。

This article是通過引用傳遞一個平衡和快速閱讀(我不能說,如果這是最好的 - 這只是第一個體面的一個,我發現)

+0

哦,當然!謝謝! – HighLife

0
  1. 如果在第一次調用newkey時爲null,則root將保持爲空。確保方法調用是正確的。

  2. 我會把別的而不是別的如果。如果它是一棵二叉樹,則它等於,大於或小於。

  3. 它是否進入Insert_helper?爲什麼你不包括它,看起來很重要?我猜想它至少得到了這麼多。

+0

對不起,應該插入不insert_helper,並且它不會插入它。如果我以root身份傳入tree_root,它始終爲空,並將root設置爲newkey,但不是tree_root。 – HighLife

0
root = newKey; 

這不修改實際的根。它只是修改函數參數,它是您在調用intsert函數時指定的指針副本。

正確的版本會看起來是這樣的:

private: 
void tree::insert_helper(key **root, key *newkey, int disc) { 
    if ((*root) == NULL) { 
    *root = key; 
    } else if (newkey->cord[disc] <= root->cord[disc]) { 
    insert_helper(&((*root)->left), newkey, (disc+1)%4); 
    } else { 
    insert_helper(&((*root)->right), newkey, (disc+1)%4); 
    } 
} 

public: 
void tree::insert(key *newKey, int disc) { 
    insert_helper(&tree_root, newkey, disc); 
} 

而且你必須要確保的「鑰匙」 constructol的左側和右側設置爲NULL。並且樹的構造函數應該爲tree_root設置NULL