Step1 : Find the level of the node and parent of the node.
Step 2 : Pass the level and parent. Traverse the tree and print the node if it is at the level passed and does not have same parent.
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<<root->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)< 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,9);
make_tree(&root,2);
make_tree(&root,1);
make_tree(&root,33);
print_tree(root);
int level=0;
struct node* temp=find_level_and_parent(root,44,&level);
if(temp!=NULL)
{
inorder(root,0,level,temp);
return 0;
}
return 1;
}
Tested code and is working fine.