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:

  1. Perform the Post Order Traversal of the given tree and find the distance between the repeated pairs of nodes.
  2. Find the nodes that are repeated in the tree using unordered_map.
  3. For each repeated node of a particular value, find the maximum possible distance between any pair.
  4. If that distance is > D, print “No”.
  5. If no such node value is found having a pair containing that value, exceeding **D, **then print “Yes”.

#greedy #recursion #searching #tree #binary tree #frequency-counting #postorder traversal #tree-traversal

Check if all the Nodes in a Binary Tree having common values are at least D distance apart
1.50 GEEK