Can you explain this example

Answer point wise, using example.

Q1: i dont understand K-L-1. Q2: WHY L-1, Q3: WHAT IS L ? AND Q4: WHY -1 ?


Q5: can u point out L,L-1 using this example. Take target=7 and k=4
Q6: Can u explain this " From root , say the target node is at depth 3 in the left branch. It means that any nodes that are distance K - 3 in the right branch should be added to the answer. " ?

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.

  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.

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.