Help with Tree/Objects
Sep 7, 2016 at 8:23pm UTC
Hello, I need to fetch all the elements of the tree.
1 2 3 4
Tree is such that 0
1 2
3 4 5 6
and so on.
My fetch function goes on deepest towards left while collecting roots..then the right. However, I am facing a problem with cloning of objects. I am not even sure that is the right approach.
I have commented out my final fetch function. and I am trying it on a simple example(I have marked below)
Could you please suggest if the approach is right. If yes, how do I get past it?
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 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142
#include<iostream>
#include<cstdio>
#include<cstdlib>
using namespace std;
class node
{
public :
node* left;
node* right;
node* parent;
int data;
void insertl(node* lnode)
{
this ->left=lnode;
}
void insertr(node* rnode)
{
this ->right=rnode;
}
void ap(node* pnode)
{
this ->parent = pnode;
}
void printdata()
{
cout<<"Self : " <<this <<"\n" ;
cout<<"Data : " <<this ->data<<"\n" ;
cout<<"Left : " <<this ->left<<"\n" ;
cout<<"Right : " <<this ->right<<"\n" ;
cout<<"Parent : " <<this ->parent<<"\n" ;
}
};
/*
void fetch(node root1)
{
node root;
node curr_node;
root=root1;
int done=0;
int d;
int xx[1000000];
int xx_ind =0;
int x[1000000];
while(not done)
{
if (root.data)
{
curr_node = root;
root = root.left;
if (root.data)
{
d = root.data;
xx[xx_ind] = d;
xx_ind = xx_ind + 1;
cout<<d;
}
}
else
{
root = curr_node.parent;
if (root.data)
{
curr_node = root;
root=root.right;
if (root.data)
{
d = root.data;
xx[xx_ind] = d;
xx_ind = xx_ind + 1;
cout<<d;
}
}
else
{
done=1;
}
}
}
}
*/
int main()
{
int num=10; //No. of nodes
node t[num];
// Making of tree
for (int i=0;i<num;i++)
{
t[i].data=i;
}
for (int i=0;i<num;i++)
{
if ((2*i)+1 < num)
{
t[i].insertl(&t[(2*i)+1]);
t[(2*i)+1].ap(&t[i]);
}
else
{
t[i].insertl(NULL);
t[(2*i)+1].ap(&t[i]);
}
if ((2*i)+2 < num)
{
t[i].insertr(&(t[(2*i)+2]));
t[(2*i)+1].ap(&t[i]);
}
else
{
t[i].insertr(NULL);
t[(2*i)+1].ap(&t[i]);
}
}
t[0].printdata();
t[1].printdata();
cout<<"t[0] data : " <<t[0].data;
t[0]=t[0].left; //// <<<<<<<------- This particular statement
t[0].printdata();
//cout<<&t[1];
//cout<<"left::"<<&(t[0].left);
//t[0]=&(t[0].left);
//t[0].printdata();
//fetch(0);
for (int i=0;i<num;i++)
{
t[i].printdata();
}
return 0;
}
Thank you, so much!!
Cheers
Last edited on Sep 7, 2016 at 8:49pm UTC
Topic archived. No new replies allowed.