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

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 
 

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”.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to implement
// the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Structure of a Tree node
struct Node {
    int key;
    struct Node *left, *right;
};
 
// Function to create a new node
Node* newNode(int key)
{
    Node* temp = new Node;
    temp->key = key;
    temp->left = temp->right = NULL;
    return (temp);
}
 
// Function to count the frequency of
// node value present in the tree
void frequencyCounts(unordered_map<int, int>& map,
                     Node* root)
{
    if (root == NULL)
        return;
    map[root->key]++;
 
    frequencyCounts(map, root->left);
    frequencyCounts(map, root->right);
}
 
// Function that returns the max distance
// between the nodes that have the same key
int computeDistance(Node* root, int value)
{
    if (root == NULL) {
        return -1;
    }
 
    int left
        = computeDistance(root->left, value);
 
    int right
        = computeDistance(root->right, value);
 
    // If right and left subtree did not
    // have node whose key is value
    if (left == -1 && right == -1) {
 
        // Check if the current node
        // is equal to value
        if (root->key == value) {
            return 1;
        }
        else
            return -1;
    }
 
    // If the left subtree has no node
    // whose key is equal to value
    if (left == -1) {
        return right + 1;
    }
 
    // If the right subtree has no node
    // whose key is equal to value
    if (right == -1) {
        return left + 1;
    }
    else {
        return 1 + max(left, right);
    }
    return -1;
}
 
// Function that finds if the distance
// between any same nodes is at most K
void solve(Node* root, int dist)
{
 
    // Create the map to look
    // for same value of nodes
    unordered_map<int, int> map;
 
    // Counting the frequency of nodes
    frequencyCounts(map, root);
    int flag = 0;
 
    for (auto it = map.begin();
         it != map.end(); it++) {
 
        if (it->second > 1) {
 
            // If the returned value of
            // distance is exceeds dist
            int result
                = computeDistance(root, it->first);
 
            if (result > dist || result == -1) {
                flag = 1;
                break;
            }
        }
    }
 
    // Print the result
    flag == 0 ? cout << "Yes\n" : cout << "No\n";
}
 
// Driver Code
int main()
{
    Node* root = newNode(1);
    root->left = newNode(2);
    root->right = newNode(3);
    root->left->left = newNode(4);
    root->left->right = newNode(3);
    root->right->right = newNode(4);
    root->right->left = newNode(4);
 
    int dist = 7;
 
    solve(root, dist);
 
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to implement
// the above approach
import java.util.*;
 
class GFG{
 
// Structure of a Tree node
static class Node
{
    int key;
    Node left, right;
};
 
// Function to create a new node
static Node newNode(int key)
{
    Node temp = new Node();
    temp.key = key;
    temp.left = temp.right = null;
    return (temp);
}
 
// Function to count the frequency of
// node value present in the tree
static void frequencyCounts(HashMap<Integer,
                                    Integer> map,
                            Node root)
{
    if (root == null)
        return;
         
    if(map.containsKey(root.key))
        map.put(root.key, map.get(root.key) + 1);
    else
        map.put(root.key, 1);
 
    frequencyCounts(map, root.left);
    frequencyCounts(map, root.right);
}
 
// Function that returns the max distance
// between the nodes that have the same key
static int computeDistance(Node root, int value)
{
    if (root == null)
    {
        return -1;
    }
 
    int left = computeDistance(root.left, value);
    int right = computeDistance(root.right, value);
 
    // If right and left subtree did not
    // have node whose key is value
    if (left == -1 && right == -1)
    {
         
        // Check if the current node
        // is equal to value
        if (root.key == value)
        {
            return 1;
        }
        else
            return -1;
    }
 
    // If the left subtree has no node
    // whose key is equal to value
    if (left == -1)
    {
        return right + 1;
    }
 
    // If the right subtree has no node
    // whose key is equal to value
    if (right == -1)
    {
        return left + 1;
    }
    else
    {
        return 1 + Math.max(left, right);
    }
}
 
// Function that finds if the distance
// between any same nodes is at most K
static void solve(Node root, int dist)
{
 
    // Create the map to look
    // for same value of nodes
    HashMap<Integer,
            Integer> map = new HashMap<Integer,
                                       Integer>();
 
    // Counting the frequency of nodes
    frequencyCounts(map, root);
    int flag = 0;
 
    for(Map.Entry<Integer,
                  Integer> it : map.entrySet())
    {
        if (it.getValue() > 1)
        {
             
            // If the returned value of
            // distance is exceeds dist
            int result = computeDistance(
                         root, it.getKey());
 
            if (result > dist || result == -1)
            {
                flag = 1;
                break;
            }
        }
    }
 
    // Print the result
    if(flag == 0)
        System.out.print("Yes\n");
    else
        System.out.print("No\n");
}
 
// Driver Code
public static void main(String[] args)
{
    Node root = newNode(1);
    root.left = newNode(2);
    root.right = newNode(3);
     
    root.left.left = newNode(4);
    root.left.right = newNode(3);
    root.right.right = newNode(4);
    root.right.left = newNode(4);
 
    int dist = 7;
 
    solve(root, dist);
}
}
 
// This code is contributed by Rajput-Ji

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to implement
// the above approach
using System;
using System.Collections.Generic;
 
class GFG{
 
// Structure of a Tree node
public
 
 class Node
{
    public
 
 int key;
    public
 
 Node left, right;
};
 
// Function to create a new node
static Node newNode(int key)
{
    Node temp = new Node();
    temp.key = key;
    temp.left = temp.right = null;
    return (temp);
}
 
// Function to count the frequency of
// node value present in the tree
static void frequencyCounts(Dictionary<int, int> map,
                            Node root)
{
    if (root == null)
        return;
         
    if(map.ContainsKey(root.key))
        map[root.key] = map[root.key]+1;
    else
        map[root.key] = 1;
 
    frequencyCounts(map, root.left);
    frequencyCounts(map, root.right);
}
 
// Function that returns the max distance
// between the nodes that have the same key
static int computeDistance(Node root, int value)
{
    if (root == null)
    {
        return -1;
    }
 
    int left = computeDistance(root.left, value);
    int right = computeDistance(root.right, value);
 
    // If right and left subtree did not
    // have node whose key is value
    if (left == -1 && right == -1)
    {
         
        // Check if the current node
        // is equal to value
        if (root.key == value)
        {
            return 1;
        }
        else
            return -1;
    }
 
    // If the left subtree has no node
    // whose key is equal to value
    if (left == -1)
    {
        return right + 1;
    }
 
    // If the right subtree has no node
    // whose key is equal to value
    if (right == -1)
    {
        return left + 1;
    }
    else
    {
        return 1 + Math.Max(left, right);
    }
}
 
// Function that finds if the distance
// between any same nodes is at most K
static void solve(Node root, int dist)
{
 
    // Create the map to look
    // for same value of nodes
    Dictionary<int,
            int> map = new Dictionary<int, int>();
 
    // Counting the frequency of nodes
    frequencyCounts(map, root);
    int flag = 0;
 
    foreach(KeyValuePair<int, int> it in map)
    {
        if (it.Value > 1)
        {
             
            // If the returned value of
            // distance is exceeds dist
            int result = computeDistance(
                         root, it.Key);
 
            if (result > dist || result == -1)
            {
                flag = 1;
                break;
            }
        }
    }
 
    // Print the result
    if(flag == 0)
        Console.Write("Yes\n");
    else
        Console.Write("No\n");
}
 
// Driver Code
public static void Main(String[] args)
{
    Node root = newNode(1);
    root.left = newNode(2);
    root.right = newNode(3);
     
    root.left.left = newNode(4);
    root.left.right = newNode(3);
    root.right.right = newNode(4);
    root.right.left = newNode(4);
 
    int dist = 7;
 
    solve(root, dist);
}
}
 
// This code is contributed by gauravrajput1

chevron_right


Output: 

Yes



 

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.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : Rajput-Ji, GauravRajput1