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

📅  最后修改于: 2021-09-06 11:30:01             🧑  作者: Mango

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

例子:

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

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

下面是上述方法的实现:

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)

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live