I'm trying to create a function that inserts a key struct into a tree. The function sets the root correctly, but does not set the branches when called again with another key. Here is the code:
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);
};
insert function from tree class:
void tree::insert(key *root, key *new开发者_如何学Ckey, 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);
}
I'm a little inexperienced with C++ pointers and was wondering how I could fix this code so that it will fill the tree correctly?
I'm not entirely sure about your approach here, but to help get you on your feet, it would help to use a function signature of:
void insert(key*& root, key *newkey, int disc);
This passes the root pointer by reference, which means that changes made inside the function will "stick" to the variable you passed in.
Your function as it stands modifies a function-local variable, without those changes propagating.
This article is a balanced and quick read on passing by reference (I can't say if it's the best - it was just the first decent one I found)
If on the first call newkey is null, root will stay null. Make sure method call is correct.
I would put an else rather than an else if. If it is a binary tree it is either equal, greater, or less than.
Does it get into Insert_helper or not? Why did you not include it, seems important? I would guess it is getting at least that far.
root = newKey;
This do not modify actual root. It just modify function argument which is a copy of pointer you specify when call intsert function.
Correct version would looks something like this:
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 );
}
Also you have to be sure that 'key' constructol set NULL for left and right. And tree constructor should set NULL for tree_root
精彩评论