Node at distance K from Leaf Node
Explanation :
Here we are traversing the tree and whenever we detect a left node we print the value stored in array at position pathLen-k-1.
While traverse we are filling array path[]
Why ?
pathLen-k-1 :
pathLen = length till current leaf node
k- node
-1 : exclude this node
Code:
void kDistantFromLeafUtil(Node* node, int path[], bool visited[],
int pathLen, int k)
{
if(node==NULL)
{
return;
}
path[pathLen]=node->key;
visited[pathLen++]=false;
if(node->left==NULL && node->right==NULL && pathLen-k-1>=0 && !visited[pathLen-k-1])
{
cout<<path[pathLen-k-1]<<" ";
++counter;
visited[pathLen-k-1]=true;
return;
}
kDistantFromLeafUtil(node->left,path,visited,pathLen,k);
kDistantFromLeafUtil(node->right,path,visited,pathLen,k);
}
0 Comments:
Post a Comment