For 1. K - L- 1 is done because in our printing nodes function for the other subtree , the one that doesn’t contain target node, we are printing a node only when count becomes zero.So, if target node is 8(say) and we want to print nodes at 3 distance then for root we get L = 2 to 8 node, we call print function to root right subtree with count of nodes that are to be travelled in the left subtree as 3-2-1=0 , so we will print 5. since we will call printsubtreenodeswithdistancek(root->right,0).
3.L reprsent whether the target node is in left subtree of given node or not.If L is -1 that means it doesn’t exist in left subtree of current node.Else it reprsent distance of the target node in the left subtree.So , for node 1 and target node 0, L is 1 as distance of 0 from 1 in the left subtree is 1.
- We do K-L-1 as we are making a call to other subtree of the given node(the subtree that deesn’t contain the target node) and 1 distance is used in going from current node to its left or right child.
for eg.for distance as 3 from 1, from root we pass 3 - 1 -1 to printsubtreewithdistancek function as distance of 5 from 1 is 2 and not 1.
6.It is quite obvious why it works as from current node to reach the target node you need to travel 3 and if you travel k - 3 in the right.Then from that node in the right to reach the target node we will first travel k-3 to reach root then 3 in left of root.
So total distance is k-3+3=k.So that’s why all node with k-3 should be added.