#include <iostream>
#include <typeinfo>
#include <math.h>
using namespace std;
struct node
{
int element;
node * leftnode;
node * rightnode;
}; //end struct
void createtree(int n, node * a, int max)
{
if (n < max)
{
if (n == 0)
{
a->element = pow(2,max-1);
//cout << "parent node's element == "<<a->element<<endl;
createtree(1,a,max);
} //end if
else
{
a->leftnode = new(nothrow) node;
a->rightnode = new(nothrow) node;
node * l = a->leftnode;
node * r = a->rightnode;
l->element = a->element-pow(2,max-(n+1));
r->element = a->element+pow(2,max-(n+1));
//cout << "the element for the leftnode of level "<<n<<" is "<<l->element<<endl;
//cout << "the element for the rightnode of level "<<n<<" is "<<r->element<<endl;
if (n < max-1)
{
createtree(n+1,l,max);
createtree(n+1,r,max);
} //end inner if
} //end else
} //end if
} //end createtree
void inorder(node * a)
{
//Remember, this should print the first child, then the parent, and then the other child.
//To do this, it must go to the lowest level first.
//After that, access the parent node
//Finally, go to the childnode.
//First, make the necessary declarations...
node * templeft = a->leftnode;
node * tempright = a->rightnode;
//if the pointer is not null
if (a != 0)
{
inorder(templeft);
//inorder(a->leftnode);
cout << a->element << endl;
//inorder(a->rightnode);
inorder(tempright);
} //end if
} //end inorder
int main()
{
int x;
cout << "Enter the number of levels of nodes (include parent node): ";
cin >> x;
node * t;
t = new(nothrow)node;
createtree(0,t,x);
inorder(t);
//This is test code; I did this to test my idea out before the implementation took place.
node b;
b.element = 32;
b.leftnode = new(nothrow) node;
b.rightnode = new(nothrow) node;
node * l = b.leftnode;
node * r = b.rightnode;
l->element = 16;
r->element = 48;
cout << "l->element == " << l->element << endl;
cout << "r->element == " << r->element << endl;
return 0;
}
(Sorry for all the comments.)
It is throwing a segmentation fault on the
node * templeft = a->leftnode;statement. Even if I forgo the use of temporary pointers (and just use a->leftnode, a->rightnode directly), it throws a segmentation fault on the
inorder(a->leftnode);statement. I have no idea why this is; I would think that it would be because the compiler doesn't know what a->leftnode, a->rightnode are, but I might be wrong. Remember that inorder(tree * a) is supposed to be PRINTING THE BINARY TREE via in-order traversal. I couldn't just use leftnode,rightnode = new(nothrow)node tree. I am out of ideas; can anyone help?
This post has been edited by IceHot: 26 December 2012 - 09:15 AM

New Topic/Question
Reply



MultiQuote





|