Can you tell me which test case i am missing?


After finding the target and printing the nodes below it, I return the distance of next node from next ancestor. Then print the nodes at that distance in other side and return 1 lesser distance to next ancestor. If distance is 0, then print ancestor and return -1 as no more nodes can be found after that. I got 2 test cases right out of 4.

@alien
Can you explain your thought process a bit more clearly? I will be able to debug it much faster

First create a tree from pre order and inorder array.
Count is a global int which couts 0 if no node is found at a distance k
nodesAtDistanceK first searches the target in the tree. If you reach any end of the tree (NULL) return -1 indicating Target was not found. Then search in the other side, if not found return -1 to parent.
If the target is found print the nodes at a distance k below it and return k-1 to the immediate ancestor, which is the distance at which next node will be found from the ancestor.
If k is 0 then ancestor is one of the answer, print it and return -1 as there can’t be anymore nodes at a distance k from our Target node.
If k is not zero then the print all the nodes at a distance k-1 from the ancestor in opposite direction where we found our Target node and return k-1-1 to it’s parent.

First create a tree from pre order and inorder array. Count is a global int which couts 0 if no node is found at a distance k nodesAtDistanceK first searches the target in the tree. If you reach any end of the tree (NULL) return -1 indicating Target was not found. Then search in the other side, if not found return -1 to parent. If the target is found print the nodes at a distance k below it and return k-1 to the immediate ancestor, which is the distance at which next node will be found from the ancestor. If k is 0 then ancestor is one of the answer, print it and return -1 as there can’t be anymore nodes at a distance k from our Target node. If k is not zero then the print all the nodes at a distance k-1 from the ancestor in opposite direction where we found our Target node and return k-1-1 to it’s parent.

@alien
Your code is absolutely correct barring one error. The elements need to be printed in a sorted order.
Please pass a vector to the function and store the elements in the vector. Sort them once the traversal is over and print them.

If my answer was able to resolve your query, please mark the doubt as resolved.

Thanks! <insert atleast 20 characters>

1 Like