Given a Binary Tree and an integer D, the task is to check if the distance between all pairs of same node values in the Tree is ? D or not. If found to be true, then print Yes. Otherwise, print No.
Examples:
Input:_ D = 7 _
1
/ \
2 3
/ \ / \
4 3 4 4
Output:_ Yes _
Explanation:
_The repeated value of nodes are 3 and 4. _
_The distance between the two nodes valued 3, is 3. _
_The maximum distance between any pair of nodes valued 4 is 4. _
Therefore, none of the distances exceed 7
Input:_ D = 1 _
3
/ \
3 3
\
3
Output:_ No _
Recommended: Please try your approach on {IDE} first, before moving on to the solution.
**Approach: **
The idea is to observe that the problem is similar to finding the distance between two nodes of a tree. But there can be multiple pairs of nodes for which we have to find the distance. Follow the steps below:
#greedy #recursion #searching #tree #binary tree #frequency-counting #postorder traversal #tree-traversal