### binary tree questiom

hi guys,

my question relates to the main function why do I have to set passIn = to tree.addNode(passIn,1) for this code to work

why can't I just say

tree.addNode returns a newNode in the first case,when we pass in the Node pointer passIn we are passing by reference since pointers are passed by reference so how come we don't have to say passIn = tree.addNode(passIn,3); and for subsequent values?

why do we have to to do this the first time around?

for example when I change passIn = tree.addNode(passIn,1) to tree.adNode(passIn,1) 7 is found does not display in the console

thanks

 ``12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576`` `````` #include using namespace std; class Node{ public: int num; Node* right; Node* left; }; class Tree{ public: Node* addNode(Node* tree,int num){ if(tree == NULL){ Node* newNode = new Node(); newNode->num = num; newNode->left = NULL; newNode->right = NULL; return newNode; } if(tree->num < num){ tree->left = addNode(tree->left,num); } else{ tree->right = addNode(tree->right,num); } return tree; } Node* search(Node* tree,int num){ if(tree == NULL){ return NULL; } if(tree->num == num){ cout << "found " << num << endl; return tree; } if(tree->num < num){ return search(tree->left,num); }else{ return search(tree->right,num); } } }; int main() { Tree tree; Node* passIn = NULL; passIn = tree.addNode(passIn,1); tree.addNode(passIn,3); tree.addNode(passIn,5); tree.addNode(passIn,7); tree.search(passIn,7); }``````
Sorry for my English...
First of all, what is the reason to have a Tree class? It doesn't have any fields to hold values and all methods are public. But okay... Let's go to your question.
 we are passing by reference since pointers are passed by reference

Emm... You can pass object by value, by pointer or by reference, it's right. And in your example you're passing object by pointer. But pointer as it is passing by value. So you can change it inside function but it won't change outside. Btw if you change object that pointed by it of course it will change.
Also if it wouldn't be so... addNode method doesn't change value of tree at all - it only add a pointer to a new Node to apropriate current node.

So your passIn remains NULL until you set it by returned pointer.
his tree is made of nodes which contain ints. So it does hold values. This is a pretty typical schoolwork tree setup.
Registered users can post here. Sign in or register to post.