只用1

时间:2015-11-19 13:44:51

标签: algorithm recursion tree

我有一棵树,只包含二进制数作为节点数据。现在我必须找到路径的最大长度,该路径只包含节点值为1且路径必须连续的节点,即路径中不应包含任何零。

例如,让我们考虑一下这个树:

root->data = 0;
root->left->data = 1;
root->right->data = 0;
root->left->left->data = 1;
root->left->right->data = 1;
root->left->left->left->data = 1;
root->left->right->left->data = 1;
root->left->right->right->data = 0;

上面树的答案应该是5。 请参考下面给出的链接中的图:

Click this for more detail

我该怎么做?

3 个答案:

答案 0 :(得分:1)

基本理念:

int GetDepthWithCondition(Node node)
{
    if (node.Data == 0)
        return -100000;
    return 1 + Math.Max(GetDepthWithCondition(node.RightSon), 
                        GetDepthWithCondition(node.LeftSon));
} 

答案 1 :(得分:1)

你的例子很奇怪。当你的根有0时,我不知道答案是5,它应该是0.另外,它应该只有4,因为如果根是1,最长的路径是沿着整个左侧。

无论如何,这基本上是在强制值为1时找到树的高度。这是diameter of a binary tree的变体,可以通过修改基本解决方案来实现:

public int MaxDiameterWithOnes(Node node)
{
    if (node == null || node.Data == 0)
        return 0;
    return 1 + Math.Max(MaxDiameterWithOnes(node.Left), MaxDiameterWithOnes(node.Right));
}

您可以使用上面链接中的第二种方法对其进行修改,以提高效率。

答案 2 :(得分:0)

算法可以是以下(伪代码):

maxPath tree | treeHasNoChildren = []               
             | data == 0 = []
             | otherwise = 
                 takeSolutionHavingMaxLength (
                   left:maxPath (left tree), 
                   right:maxPath (right tree)
                 )
相关问题