Kthlevel print please explain

unable to get the code
void printTreeAtKthLevel(node * root,int k)
{
if(root)
{
if(k==1)
{ cout<data<<" ";

}
printTreeAtKthLevel(root->left,k-1);
printTreeAtKthLevel(root->right,k-1);

}

Let’s say the tree looks something like this
image
You want to print the 3rd level, so you take root as kth level i.e., 3rd level, basically, you are printing k-2th level where k becomes 1. If you want to print let’s say the 4th level, you take root level as k = 4 and go to the node when k becomes 1.
/*
printTreeAtKthLevel(root->left, k -1);
printTreeAtKthLevel(root->right, k -1);
*/
This part of code is simply traversing through all the nodes as in preorder traversal.
If you want me to explain the whole traversal process, tell me I will explain, or I would recommend watching Prateek bhaiya’s video lecture.
I guess you will understand what I am trying to explain. :slight_smile:

1 Like

No its fine i got it.