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;
};
root
/ \
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.
Function Prototype,
void initializeGrandParent(node * root)
3. Convert a binary tree into a doubly-linked list so that the order of the elements in the list should be equivalent to a zig-zag traversal of the tree
*/
#include
#include
struct Node
{
struct Node *left;
struct Node *right;
struct Node *grandparent;
int data;
};
void SetGrandParent(struct Node *);
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);
}
/* Driver program to test above functions*/
int main()
{
/* Constructed binary tree is
1
/ \
2 3
/ \ /
4 5 8
*/
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