2011-10-11 127 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