【问题标题】:find longest path of white nodes找到最长的白色节点路径
【发布时间】:2013-02-13 08:22:47
【问题描述】:

在一次采访中被问到这个问题: 给出了具有黑白节点的树。在给定的树中找到最长的白色节点路径。下面的方法是否正确或有人帮助提供更好的方法谢谢!

int Longest(node root, int max)
{
    if(root==null || root.color == black)
        return 0;
    if(root.color == white)
    {

      int curmax =1+ firstlongest(root.child) + secondlongest(root.child); 

        if(curmax>max) 
            max = curmax;
        return curmax;
    }
    if(root.color == black)
    {
        for(all children)
        {
            int curmax =1+ firstlongest(root.child) + secondlongest(root.child); 
        }
        if(curmax>max) 
            max =curmax;
        return 0;
    }
}

 int firstlongest(node* child){//will calculate first longest of children and similarly 
 secondlongest gives second.Finally max will have length of longest path.

【问题讨论】:

标签: java c algorithm


【解决方案1】:

简介:
首先记住如何在树中找到最长的路径。你取一个任意顶点v,用bfs找到离它最远的顶点u,然后找到离u最远的顶点t,再次使用 bfs,并且 (u,t) 路径将是树中最长的。我不会在这里证明它,您可以搜索它或尝试证明自己(不过,如果您在一些示例上运行它,这很明显)。

解决方案:
现在你的问题。我们不需要黑色节点,所以让我们把它们扔掉吧:) 剩下的图将是一个森林,即一组树。用已知算法为每棵树找到最长的路径,然后选择最长的。

复杂性:
所描述的算法将执行一次线性传递以删除黑色节点,并为森林中的每棵树执行两个线性 bfs,这对图中的所有节点都是线性的。总共:O(n) + O(n+m) + O(n+m) = O(n+m)

【讨论】:

  • 这听起来很奇怪。例如。如果我选择任意顶点v,如果该顶点是叶节点怎么办?我可以看到这种方法适用于无向图......但是在树中,节点通常没有对其父级的引用。因此,从叶节点启动 bfs 绝对不会产生任何结果。
  • @Alderath:是的,当然所有这些都是关于无向图的。在有向树中找到最长的路径完全没有意义——它只是树的高度
【解决方案2】:

您的程序似乎只计算向下的路径。假设所有节点都是白色的,它将错过这棵树中最长的路径:

      r
     /
    a
   / \
  b   c
 /     \
d       e  

最长的路径是dbace

【讨论】:

  • 那我想如果你也能上去,这将成为NP难题。
  • @Android 我对此表示怀疑。您必须将此视为图表上的问题。删除每个黑色节点。现在,对于每个剩余的森林,递归地计算最长的路径。取最长的找到的路径。问题归结为找到最长的路径。
  • 哦。我忘记了白色节点..谢谢
【解决方案3】:

代码对我来说似乎不正确。以下部分:

if(root.color == black)
{
    for(all children)
    {
        int curmax = max(longest(root.child[i], max));
    }
    if(curmax>max) 
        max =curmax;
    return 0;
}

永远不会被执行,因为如果root.color == black方法会提前返回0。

我会这样做:

private static int longestWhitePathFromRootLength (Node node)
{
    if (node.color == BLACK)
        return 0;
    else // node.color == WHITE
    {
        int l = 0;

        for (Node n: node.children)
        {
            l = Math.max (l, longestWhitePathFromRootLength (n));
        }

        return l + 1;
    }
}

public static int longestWhitePathLength (Node node)
{
    int l = 0;

    for (Node n: node.children)
    {
        l = Math.max (l, longestWhitePathLength (n));
    }

    return Math.max (l, longestWhitePathFromRootLength (node));
}

【讨论】:

  • 这段代码可以优化——它是不必要的二次方。对于高度为 n 的树,longestWhitePathFromRootLength() 将在每个级别上被调用,然后下降到叶子,从而给出 Theta(n^2) 运行时间。
猜你喜欢
  • 2011-03-08
  • 2011-04-26
  • 2011-03-08
  • 2019-06-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-06
  • 1970-01-01
相关资源
最近更新 更多