Given a Binary Tree and an integer D, the task is to check if the distance between all pairs of the same node values in the Tree is? D or not. If found to be true, then print Yes. Otherwise, print No.
Input: D = 7
1 / \ 2 3 / \ / \ 4 3 4 4
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
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:
- Perform the Post Order Traversal of the given tree and find the distance between the repeated pairs of nodes.
- Find the nodes that are repeated in the tree using unordered_map.
- For each repeated node of a particular value, find the maximum possible distance between any pair.
- If that distance is > D, print “No”.
- If no such node value is found having a pair containing that value, exceeding D, then print “Yes”.
Below is the implementation of the above approach:
Time Complexity: O(N2)
Auxiliary Space: O(1)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.