算法难题 : Distinct nodes in a subtree

标签 algorithm time-complexity

我正在尝试解决这个问题:

You are given a rooted tree consisting of n nodes. The nodes are numbered 1,2,…,n, and node 1 is the root. Each node has a color.

Your task is to determine for each node the number of distinct colors in the subtree of the node.

强力解决方案是为每个节点存储一个集合,并在深度优先搜索中累积合并它们。这将在 n^2 中运行,效率不高。

如何有效地解决这个问题(以及同类问题)?

最佳答案

对于每个节点,

  1. 递归遍历左右节点。
  2. 让每个调用返回一个颜色的哈希集。
  3. 在每个节点,合并左子集、右子集。
  4. 更新 HashMap 中当前节点的计数。
  5. 添加当前节点的颜色并返回集合。

示例 C# 代码:

public Dictionary<Node, Integer> distinctColorCount = new ...

public HashSet<Color> GetUniqueColorsTill (TreeNode t) {
    // If null node, return empty set.
    if (t == null) return new HashSet<Color>();

    // If we reached here, we are at a non-null node.
    // First get the set from its left child.
    var lSet = GetUniqueColorsTill(t.Left);

    // Second get the set from its right child.
    var rSet = GetUniqueColorsTill(t.Right);

    // Now, merge the two sets.
    // Can be a little clever here. Merge smaller set to bigger set.
    var returnSet = rSet;
    returnSet.AddAll(lSet);

    // Put the count for this node in the dictionary.
    distinctColorCount[t] = returnSet.Count;    

    // Finally, add the color of current node and return.
    returnSet.Add(t.Color);

    return returnSet;
}

您可以使用主定理准确地计算出复杂性,就像 @user58697 对您的问题的评论一样。 This这是我很久以前写的另一个答案,它解释了主定理,如果您需要复习的话。

关于算法难题 : Distinct nodes in a subtree,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61858896/

相关文章:

java - 寻找滑动窗口中的最大值

algorithm - 3D 中两个凸多边形之间的距离

java - 如何找到指定月份的星期几的索引?

algorithm - 给定顶点的度数,检查是否存在无向图

algorithm - 我如何计算这两小段代码的时间复杂度?

java - 为什么这个 O(N^2) 算法运行得这么快?

algorithm - 将随机范围从 1-5 扩展到 1-7

java - 用Java实现RSA算法

algorithm - 检查某个数字是否适合大量范围的最有效方法

algorithm - 如果 n > 3,求关系 T (n) =T (n-1)+T(n-2)+T(n-3) 的时间复杂度