everybody! Really, I just want to understand what is going on with this references and pointers. Can you explain me, why in one case all is workking fine, but in another I receive nothing I will start with working case. So, there is a program (this is not mine):
#include <iostream>
#include <conio.h>
using namespace std;
struct node{
double data;
node *left;
node *right;
};
node *tree = NULL;
void push(int a, node **t)
{
if ((*t) == NULL)
{
(*t) = new node;
(*t)->data = a;
(*t)->left = (*t)->right = NULL;
return;
}
if (a > (*t)->data) push(a, &(*t)->right);
else push(a, &(*t)->left);
}
void print (node *t, int u)
{
if (t == NULL) return;
else
{
print(t->left, ++u);
for (int i=0; i<u; ++i) cout << "|";
cout << t->data << endl;
u--;
}
print(t->right, ++u);
}
int main ()
{
int n;
int s;
cout << "Enter the amount of elements ";
cin >> n;
for (int i=0; i<n; ++i)
{
cout << "Enter the value ";
cin >> s;
push(s, &tree);
}
cout << "Your binary tree\n";
print(tree, 0);
cin.ignore().get();
}
This is binary search tree made with struct, pointers and references. And it is work exactly fine But if i modify program in the way below it doesn't work. And i don't understand why, because
int *tree;
int **treePointer;
cout << (tree = *treePointer) <<endl; // Shows 1 i.e. true
Modified code:
#include <iostream>
#include <conio.h>
using namespace std;
struct node{
double data;
node *left;
node *right;
};
node *tree = NULL;
void push(int a, node *t)
{
if ((t) == NULL)
{
(t) = new node;
(t)->data = a;
(t)->left = (t)->right = NULL;
return;
}
if (a > (t)->data) push(a, (t)->right);
else push(a, (t)->left);
}
void print (node *t, int u)
{
if (t == NULL) return;
else
{
print(t->left, ++u);
for (int i=0; i<u; ++i) cout << "|";
cout << t->data << endl;
u--;
}
print(t->right, ++u);
}
int main ()
{
int n;
int s;
cout << "Enter the amount of elements ";
cin >> n;
for (int i=0; i<n; ++i)
{
cout << "Enter the value ";
cin >> s;
push(s, tree);
}
cout << "Your binary tree\n";
print(tree, 0);
cin.ignore().get();
}
As you see, all changes happen in push function argument. Why it is not working?
I am expecting that original program and modified will work the same