Geeksforgeeks

Error

×

Leaderboard

Showing:

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

@Ibrahim Nash | 6420 |

@blackshadows | 6380 |

@mb1973 | 5704 |

@Quandray | 5245 |

@akhayrutdinov | 5111 |

@saiujwal13083 | 5046 |

@sanjay05 | 3762 |

@kirtidee18 | 3673 |

@marius_valentin_dragoi | 3523 |

@mantu_singh | 3514 |

@sushant_a | 3459 |

Complete Leaderboard | |

Handle | Score |

@cfwong8 | 1156 |

@gurshehzadsingh | 676 |

@nithinreddy3210 | 642 |

@jha8768 | 577 |

@Run_for_life | 574 |

@divyagupta221100 | 557 |

@AkashLahoty | 553 |

@aayushdesai01 | 526 |

@riyakumaribkj | 526 |

@2017akku | 521 |

@amansinha74458 | 503 |

Complete Leaderboard |

Given a Binary Tree and a positive integer **k**. The task is to count all distinct nodes that are distance k from a leaf node. A node is at k distance from a leaf if it is present k levels above the leaf and also, is a direct ancestor of this leaf node. If k is more than the height of Binary Tree, then nothing should be counted.

**Example 1:**

**Input:
** 1
/ \
2 3
/ \ / \
4 5 6 7
\
8
K = 2
**Output: **2**
Explanation: **There are only two unique
nodes that are at a distance of 2 units
from the leaf node. (node 3 for leaf
with value 8 and node 1 for leaves with
values 4, 5 and 7)
Note that node 2
isn't considered for leaf with value
8 because it isn't a direct ancestor
of node 8.

**Example 2:**

**Input:
** 1
/
3
/
5
/ \
7 8
\
9
K = 4
**Output: **1**
Explanation: **Only one node is there
which is at a distance of 4 units
from the leaf node.(node 1 for leaf
with value 9)

**Your Task:**

You don't have to read input or print anything. Complete the function **printKDistantfromLeaf() **that takes **root node **and** k **as inputs and **returns **the number of nodes that are at distance k from a leaf node. Any such node should be counted only once. For example, if a node is at a distance k from 2 or more leaf nodes, then it would add only 1 to our count.

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

**Expected Auxiliary Space: **O(Height of the Tree).

**Constraints:**

1 <= N <= 10^{5}

**Note: **The **Input/Output **format and **Example **are given are used for the system's internal purpose, and should be used by a user for **Expected Output **only. As it is a function problem, hence a user should not read any input from the stdin/console. The task is to complete the function specified, and not to write the full code.

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?

YesLoading...

Node at distance

...