Review the code

could u please review my code given in the link below and tell me possible changes that I need to make in order to get the correct output.

link for the code is : https://ide.codingblocks.com/s/443889

you are getting ArrayIndexOutOfBoundsException error for your construct for case like

15
12 10 17 22 20 85 74 38 23 64 46 51 65 99 87
10 12 17 20 22 23 38 46 51 64 65 74 85 87 99
10
10 2
17 3
22 4
20 2
23 5
46 4
51 2
65 3
99 1
85 2

For this problem we can encounter two kinds of nodes .

  • Nodes in the subtree rooted with target node.
  • Other nodes, may be an ancestor of target, or a node in some other subtree.

Finding the first type of nodes is easy to implement. Just traverse subtrees rooted with the target node and decrement k in recursive call. When the k becomes 0, print the node currently being traversed .
For the output nodes not lying in the subtree with the target node as the root, we must go through all ancestors. For every ancestor, we find its distance from target node, let the distance be d, now we go to other subtree (if target was found in left subtree, then we go to right subtree and vice versa) of the ancestor and find all nodes at k-d distance from the ancestor.

you can refer to this approach if you need