📌  相关文章
📜  检查二叉树中所有具有共同值的节点是否至少相距D距离

📅  最后修改于: 2021-05-06 20:54:09             🧑  作者: Mango

给定二叉树和整数D ,任务是检查树中相同节点值的所有对之间的距离是否为? D或没有。如果发现是真的,则打印“是” 。否则,打印No。

例子:

方法:
想法是观察到问题类似于找到树的两个节点之间的距离。但是可能必须有多对节点,我们必须为其寻找距离。请按照以下步骤操作:

  1. 执行给定树的后遍历并找到重复的节点对之间的距离。
  2. 使用unordered_map查找在树中重复的节点。
  3. 对于特定值的每个重复节点,找到任意一对之间的最大可能距离。
  4. 如果该距离> D ,则打印“否”。
  5. 如果未找到包含超过该值的对的节点值则打印“是”。

下面是上述方法的实现:

C++
1
              /   \ 
             2     3
            / \   /  \ 
           4   3  4   4


Java
3
         / \
        3   3
             \
              3


Python3
// C++ program to implement
// the above approach
#include 
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& 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 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;
}


C#
// 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 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 map = new HashMap();
 
    // Counting the frequency of nodes
    frequencyCounts(map, root);
    int flag = 0;
 
    for(Map.Entry 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


输出:
# Python3 program to implement
# the above approach
 
# Structure of a Tree node
# Function to create a new node
mp = {}
 
class newNode:
   
    def __init__(self, key):
       
        self.key = key
        self.left = None
        self.right = None
 
# Function to count the frequency
# of node value present in the tree
def frequencyCounts(root):
   
    global mp
     
    if (root == None):
        return
       
    mp[root.key] = mp.get(root.key, 0) + 1
    frequencyCounts(root.left)
    frequencyCounts(root.right)
 
# Function that returns the max
# distance between the nodes that
# have the same key
def computeDistance(root, value):
   
    if (root == None):
        return -1
 
    left = computeDistance(root.left,
                           value)
    right = computeDistance(root.right,
                            value)
 
    # If right and left subtree
    # did not have node whose
    # key is value
    if (left == -1 and
        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
def solve(root, dist):
   
    # Create the mp to look
    # for same value of nodes
    global mp
 
    # Counting the frequency
    # of nodes
    frequencyCounts(root)
    flag = 0
 
    for key,value in mp.items():
        if(value > 1):
           
            # If the returned value of
            # distance is exceeds dist
            result = computeDistance(root,
                                     key)
 
            if (result > dist or
                result == -1):
                flag = 1
                break
 
    # Print the result
    if flag == 0:
        print("Yes")
    else:
        print("No")
 
# Driver Code
if __name__ == '__main__':
   
    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)
    dist = 7
    solve(root, dist)
 
# This code is contributed by SURENDRA_GANGWAR

时间复杂度: O(N 2 )
辅助空间: O(1)