Python:计算带有多个子代的树的最大高度

时间:2018-07-30 23:58:43

标签: python tree

def __init__(self,label=None):
    self.label = label
    self.leftMostChild = None
    self.RightSibling = None


def height(self):
    if self.leftMostChild == None and self.RightSibling == None:
        return 0
    else:
        if self.leftMostChild:
            return self.leftMostChild.height() + 1

        if self.RightSibling:
            return self.RightSibling.height()

显然,高度偏移了1。当生成高度为3的树时,调用函数height会返回2。我不确定该功能在哪里做错了。

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

返回使函数立即结束。这意味着,如果节点同时具有最左侧的子级和右侧的同级,则永远不会评估右侧的同级。这是每个if / else分支只有一个返回的函数。

def height(self):
    if self.leftMostChild == None and self.RightSibling == None:
        return 0
    else:
        leftHeight = rightHeight = 0
        if self.leftMostChild:
            leftHeight =  self.leftMostChild.height() + 1

        if self.RightSibling:
            rightHeight = self.RightSibling.height()
        return max(leftHeight, rightHeight)

这可以进一步简化为:

def height(self):
    leftHeight = rightHeight = 0
    if self.leftMostChild:
        leftHeight =  self.leftMostChild.height() + 1
    if self.RightSibling:
        rightHeight = self.RightSibling.height()
    return max(leftHeight, rightHeight)