Tuesday, April 19, 2011

WAP for Given a binary tree, write a program to find the cousin nodes of the given node.

//find the level and print the cousins
#include
#include

using namespace std;

struct node{
struct node* left;
struct node* right;
int data;
};

void inorder(struct node* root,int present_level,int level,struct node* parent)
{
if(root!=NULL)
{
if(parent!=root)
inorder(root->left,present_level+1,level,parent);
if(level==present_level)
cout<data<<" ";
if(parent!=root)
inorder(root->right,present_level+1,level,parent);
}

}

void make_tree(struct node **root,int data)
{
if((*root)==NULL)
{
(*root)=new node;
(*root)->left=NULL;
(*root)->right=NULL;
(*root)->data=data;
return;
}
else
{
if(((*root)->data)make_tree(&((*root)->right),data);
else
make_tree(&((*root)->left),data);
}


}

struct node* find_level_and_parent(struct node* root,int data,int* level)
{
struct node* parent=NULL;
struct node* child=root;

while(1)
{

if(child==NULL)
return NULL;
if(child->data==data)
{
return parent;

}
if(data>child->data)
{
parent=child;
child=child->right;
*level=*level+1;

}
else if(data<=child->data)
{
parent=child;
child=child->left;
*level=*level+1;
}


}

}

int main()
{
struct node* root=NULL;
make_tree(&root,6);
make_tree(&root,8);
make_tree(&root,3);
make_tree(&root,4);
make_tree(&root,44);
make_tree(&root,34);
make_tree(&root,12);
make_tree(&root,8);
make_tree(&root,2);
make_tree(&root,1);
make_tree(&root,33);

int level=0;
struct node* temp=find_level_and_parent(root,12,&level);
if(temp!=NULL)
{
cout<<"Level="<return 0;
}

Solution Provide By Ankit From CareerCup
Run Here https://ideone.com/ybavU

2 comments :

Unknown said...

You have solved this problem considering it is BST. It wont work on binary tree

Unknown said...

@devendra ..did u tried , give me time i will check & revert :)