Challenge trees-----print nodes at distance k from given node

explain me solution to this

sure!! just give me sometime

let’s call the given node as X
There are two types of nodes that we need to consider

  1. the nodes that are k distance below X (desendants at distance k from X)
  2. the nodes that are k distance above X or in some other subtree

for (1) we can easily find the required nodes by using recursive call to the child nodes and decrementing value of k

for (2) things are just a bit complex for every ancestor say Y, of X we need to to find the distance of Y from X say d, then we need to go to the other subtree (i.e. the subtree in which X does’nt belong i.e. if X is in left Subtree of Y then consider right subtree and vice versa) and find all nodes at k-d distance from Y

yes that i ahve understood …
plz check my solution and tell me where i am wrong

for your easy understanding lemme explain it
1- i have used preorder traversal to find the node to the value given in question to be searched with their only i have also created the map for parent nodes
2- now in fine() function i have used the the level order traversal in which i have maintained queue of node and level of tree so while popping i use to check 3 conditions
1-left node…2-right node…3.parent node of that popped node
IN all 3 checks i increment the level by 1 to the level of popped node as it is the root

bro it took me 5 hours to code this solution plz tell me error as soon as possible

sure!! give me sometime i will check your code

bro check this one i have corrected some errors in this

2 middle test cases are getting failed

Hi Deepak , your code seems fine but your output is not in sorted order in the question it is mentioned that " On T lines print space separated desired output for each test case in sorted form " this is why you are getting WA .

yes bro i have corrected it and got 1 case out of 2 correct now there was one more mistake that i was not printing zero in case the there is no node at distance k

Also I can see that you did’nt consider the case in which there no node that is present at k distance as in such case it is clearly mentioned in the question that you have to print ‘0’ for such cases;

I have made some changes in your codes : https://ide.codingblocks.com/s/181706

not i got all cases correct

great!! feel free to ask in case of any doubt

can you share your whatsapp no plz sir

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.