Geeksforgeeks

Error

×

Leaderboard

Showing:

Handle | Score |
---|---|

@Ibrahim Nash | 5725 |

@blackshadows | 5685 |

@akhayrutdinov | 5111 |

@mb1973 | 4989 |

@Quandray | 4908 |

@saiujwal13083 | 4156 |

@sanjay05 | 3762 |

@marius_valentin_dragoi | 3511 |

@sushant_a | 3453 |

@KshamaGupta | 3318 |

@the_coder95 | 3302 |

Complete Leaderboard | |

Handle | Score |

@shashi1iitk | 398 |

@Suniti Jain | 114 |

@ankish2000nayak | 104 |

@gopalsethlnct | 94 |

@senthil1185 | 90 |

@esmadhan | 90 |

@gyanadipta07 | 89 |

@satwikdash2000 | 85 |

@varunmishra3040 | 83 |

@gamec1634 | 82 |

@pj_1721 | 80 |

Complete Leaderboard |

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

Login to report an issue on this page.

We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial?

Yes
Nodes at given distance in binary tree

...

Please choose 'ReadOnlyMode' if you needn't to 'Edit' the problem e.g. viewing OJ's solution, TestCase Files (TCFs), TimeLimit etc.