I built a binary tree using a root pointer.
Isn’t the root pointer supposed to be changed in all functions, since I declared it globaly? How do I achieve this?
Thanks
//Pseudocode (left, right pointers declared elsewhere)
Node * root = new Node;
Node * BST::BuildTree(int label)
{
root->left = changed;
root->right = changed;
}
Node * BST::GetNode(int label)
{
BTNode *ptr = root;
cout << root->right; //This gives me a seg fault since root is still NULL and not changed
}
This is because you haven’t assign a valid address to
root, in your code.It should point to a valid node:
And in C++, you should use unnamed namespace when you want to use a “global variable”. The benefit is that it’ll prevent name conflicts which can easily be introduced by global variables.
If you’re coding in C, I’d end up here. But since you’re using C++, there’s one thing more.
You should try your best to avoid using global variables, especially when you have lots of them which depend on each other. Usually, you can create a singleton class.
But I don’t think your case is that complicated to use a singleton. Just add an extra input parameter to your functions to indicate which node you want to operate on.