Skip to content

Instantly share code, notes, and snippets.

@shubham100795
Created February 20, 2017 17:34
Show Gist options
  • Select an option

  • Save shubham100795/67e3808d0bf8acca7fa82dd9ade520f2 to your computer and use it in GitHub Desktop.

Select an option

Save shubham100795/67e3808d0bf8acca7fa82dd9ade520f2 to your computer and use it in GitHub Desktop.
print nodes at a distance 'k' from leaf nodes
#include<iostream>
#include<set>
#include<cstdlib>
using namespace std;
struct node{
int data;
struct node *left;
struct node *right;
};
struct node *newnode(int x)
{
struct node* ptr=(struct node*)malloc(sizeof(struct node));
ptr->data=x;
ptr->left=NULL;
ptr->right=NULL;
return ptr;
}
struct node* insert(struct node *root,int x)
{
struct node* par;
if(root==NULL)
{
root=newnode(x);
return root;
}
else
{
struct node *proot=root;
while(proot!=NULL)
{
if(x<proot->data)
{
par=proot;
proot=proot->left;
}
else
{
par=proot;
proot=proot->right;
}
}
if(x<par->data)
par->left=newnode(x);
else
par->right=newnode(x);
return root;
}
}
void display(struct node *root)
{
if(root==NULL)
return;
display(root->left);
cout<<"\t"<<root->data;
display(root->right);
}
static int index=0;
void nodesatdistk(struct node *root,int *ar,int index,set<int>&s,int k)
{
if(root==NULL)
return;
ar[index++]=root->data;
if(root->left==NULL&&root->right==NULL&&(index-k-1>=0))
{
int x=ar[index-k-1];//index is now root to leaf path length
s.insert(x);
return;
}
nodesatdistk(root->left,ar,index,s,k);
nodesatdistk(root->right,ar,index,s,k);
}
int main()
{
int x;
struct node *root=NULL;
int ar[5];
set<int>st;
set<int>::iterator it;
while(1)
{
cin>>x;
if(x==-1)
break;
root=insert(root,x);
}
display(root);
cout<<endl;
nodesatdistk(root,ar,index,st,1);
for(it=st.begin();it!=st.end();it++)
{
cout<<*it<<"\t";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment