这是获取二叉树高度的好方法吗?

Mei*_*hin 2 python algorithm tree search binary-tree

我不是计算机科学学生,所以这不是家庭作业。我正在尝试自己学习这些东西,但我想确保我不会在此过程中养成坏习惯。

基本上,我有一个经典的二叉树,我想计算树的高度(或深度)。

我所说的高度是这样的:

这

这棵树的高度是3。

这是我想出的蟒蛇:

def height(node):

    #highest one of these two will be returned
    i_left = 0
    i_right = 0

    #if has left, increment and recursively move left
    if node.hasleft():
        i_left += height(node.left)
        i_left += 1

    #if has right, increment and recursively move right
    if node.hasright():
        i_right += height(node.right)
        i_right += 1

    #return the higher value
    if i_right <= i_left:
        return i_left    
    return i_right
Run Code Online (Sandbox Code Playgroud)

这个解决方案很有效,我有点喜欢它,因为它很简单,并且没有很多抽象的东西需要你思考。但是,我确实想知道这是否应该这样做。有什么方法可以改进,或者有没有更可接受的方法来实现高度函数?

Bar*_*mar 5

如果有子节点,您的代码只会将左侧或右侧节点的高度加 1。即使没有子节点,也需要为当前节点加 1。所以它不应该在if街区里。

def height(node):

    #if has left, recursively move left
    if node.hasleft():
        i_left = height(node.left)
    else:
        i_left = 0

    #if has right, recursively move right
    if node.hasright():
        i_right = height(node.right)
    else:
        i_right = 0

    #return the higher value, plus 1 for the current node.
    return 1 + max(i_left, i_right)
Run Code Online (Sandbox Code Playgroud)