Tuesday, February 28, 2012

Populate Grand Parents in Binary Tree

You are given a special kind of binary tree, in which there is another attribute, “grandparent”, which is a pointer to the grandparent of a node. The tree structure is thus,
struct Node
{
int val;
node * left;
node * right;
node * grandparent;
};

1
/ \
2 3
/ \  \
4 5 8

In the tree given to you, the grandparent attribute for each node is initialized to NULL. Write a function to initialize the grandparent attribute.
Note: The value of the “grandparent” attribute for the root and first level nodes will be NULL.

Code:
 #include <stdio.h>
#include <stdlib.h>
#include <limits.h>

struct Node
{
struct Node *left;
struct Node *right;
struct Node *grandparent;
int data;

};


int isLeaf(struct Node *n)
{
return (n->left==NULL && n->right==NULL);

}

int isAtHeightLEOne(struct Node *n)
{

return ((n==NULL) || ((n->left==NULL) ||isLeaf(n->left)) && ((n->right==NULL) || isLeaf(n->right)) );

}

void setGrand(struct Node *p, struct Node *root)
{
if(p->left)
p->left->grandparent=root;

if(p->right)
p->right->grandparent=root;

}

void SetGrandParent(struct Node *t)
{
if(isAtHeightLEOne(t))
return;

struct Node *p=t->left;

if(p)
{
setGrand(p,t);
SetGrandParent(p);

}
p=t->right;
if(p)
{

setGrand(p,t);
SetGrandParent(p);

}

}

struct Node* newNode(int data)
{
struct Node* node = (struct Node*)
malloc(sizeof(struct Node));
node->data = data;
node->left = NULL;
node->right = NULL;
node->grandparent=NULL;

return(node);
}

int main()
{

struct Node *root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
root->right->left = newNode(8);

SetGrandParent(root);

printf(" %d %d %d ",root->left->left->grandparent->data,root->left->right->grandparent->data,root->right->left->grandparent->data);

getchar();
return 0;
}

No comments:

Post a Comment