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(passIn,1);

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
  #include <iostream>
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.
Topic archived. No new replies allowed.