Initially, the grand parent node is null in the tree. you have to assign the grandparent node for all the nodes in the tree.

typedef struct Node
{
int value;

struct Node *left;
struct Node *right;
struct Node *grandparent;
} Node;

typedef Node * Tree;

inline void setGrand(const Node *p, Node *parent)
{
if(p->left)
p->left->grandparent = parent;

if(p->right)
p->right->grandparent = parent;
}

void setGrandParent(Tree t)
{
if(t == NULL)
return;

Node *p = t->left;
if(p)
{
setGrand(p, t);
setGrandParent(p); //call recursivley
}

p = t->right;
if(p)
{
setGrand(p, t);
setGrandParent(p); //call recursivley
}
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s