Reputation: 578
I'm trying to implement a binary tree in C++ and transverse it in a root-left-right manner. After I add all the nodes I get a crash at this line:
cout << r->st->st->info << endl; //trying to print root->left->left->info
My RSD function doesn't print anything. Also, I would appreciate any Visual Studio tutorials on how to use the debugger. Thank you.
#include<iostream>
using namespace std;
struct Nod{
int info;
Nod *st, *dr;
};
int read_tree(Nod *r)
{
int info;
cout << "Info: "; cin >> info;
if (info!=0)
{
r = new Nod;
r->info = info;
read_tree(r->st);
read_tree(r->dr);
}
else
return 0;
}
void RSD(Nod *r)
{
if (r != NULL)
{
cout << r->info << " ";
RSD(r->st);
RSD(r->dr);
}
}
int main()
{
Nod *r = NULL;
read_tree(r);
system("Pause");
cout << r->st->st->info << endl;
cout << r->dr->info;
RSD(r);
}
Upvotes: 0
Views: 439
Reputation: 18546
The problem is that you pass a copy of a pointer to a read_tree
function. That is, when you call read_tree(r)
in the main function, r
remains NULL
regardless of what happens inside the read_tree
function. You can fix it by passing a pointer by reference. That is, changing read_tree(Nod* r)
to read_tree(Nod*& r)
should fix it.
Upvotes: 3