BINARY SEARCH TREE - "SEARCH FUNCTION"

So I have a struct in my header file called:
1
2
3
4
5
6
7
struct TreeNode{ 
string info; 
TreeNode* left; 
TreeNode *right; 
}; 
//Then I have a pointer to root: 
TreeNode* root; 

..........................................
Then in my class file, In my constructor, I set root = NULL;

Then I have an insert function.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
void insert(TreeNode* tree, string something) 
{ 
// here I fill up the tree 
if (tree == NULL) 
{ // Insertion place found. 
tree = new TreeNode; 
tree->right = NULL; 
tree->left = NULL; 
tree->info = something; 
} 
else if (something < tree->info) 
insert(tree->left, something); // Insert in left subtree 

else 
insert(tree->right, something); // Insert in right subtree 
} 

Then I have a search function

1
2
3
4
void search(TreeNode* tree, string key) 
{ 
// here, I found that root is equal to NULL. HOW COULD IT BE NULL, I FILLED UP THE TREE IN INSERT // FUNCTION. ???????? 
}
Last edited on
I FILLED UP THE TREE IN INSERT // FUNCTION
No, you did not.
You created some new object, changed it. But root itself will not change, as you passed a copy of pointer. You need to pass either reference or pointer to pointer.
Last edited on
Hi MiiNiPaa,
thanks for the hint. But where do I pass in the reference to the pointer. During the function call? or in the function signature/prototype?
1
2
3
void insert(TreeNode*& tree, string something)  
//call as usual:
insert(tree->left, something); 


or

1
2
3
void insert(TreeNode** tree, string something)  
//Pass a pointer to TreeNode ponter:
insert(&((*tree)->left), something); //as tree is pointer to pointer 
MiiNiPaa,
Thank you so much!!!
You just saved my life :)
Topic archived. No new replies allowed.