Geeksforgeeks

Timer is Running

Given a binary tree, a target node in the binary tree, and an integer value k, find all the nodes that are at distance k from the given target node. No parent pointers are available.

**Example 1:**

Input :20 / \ 8 22 / \ 4 12 / \ 10 14 Target Node = 8 K = 2Output:10 14 22Explanation:The three nodes at distance 2 from node 8 are 10, 14, 22.

**Example 2:**

Input :20 / \ 7 24 / \ 4 3 / 1 Target Node = 7 K = 2Output:1 24

**Your Task: **

You dont need to read input or print anything. Complete the function** KDistanceNodes()** which takes the root of the tree, target and K as input parameters and returns a list of nodes at k distance from target.

**Expected Time Complexity: **O(N)

**Expected Auxiliary Space: **O(height of tree)

**Constraints:**

1 ≤ N ≤ 10^3

1 ≤ data of node ≤ 10000

1 ≤ target ≤ 10000

1 ≤ k ≤ 20

Author: Ayush Govil 1

If you have purchased any course from GeeksforGeeks then please ask your doubt on course discussion forum. You will get quick replies from GFG Moderators there.

Pathak1899 | 436 |

yashdip123 | 380 |

kirtidee18 | 377 |

ykaushik | 261 |

_saswata | 232 |

kirtidee18 | 1057 |

ykaushik | 733 |

aggarwalvatsal5 | 709 |

pmr_3689 | 570 |

harbilassingh | 530 |

blackshadows | 5456 |

Ibrahim Nash | 5450 |

akhayrutdinov | 5111 |

mb1973 | 4976 |

Quandray | 4823 |

Login to report an issue on this page.