递归和二叉树

时间:2016-05-27 16:51:17

标签: python recursion

#Get length of the longest path through recursion
def max_height(node):
    if not node:
        return 0
    left = max_height(node.left) #Base Case based on my understanding
    right = max_height(node.right) #Base Case based on my understanding
    return max_height(left, right) + 1

我一直在调用max_height来获取长度,但我收到错误。我想到了三种可能性:

1)我误解了基本案例的概念,我实际上没有基本案例。

2)我没有正确地间隔Python代码。

3)我没有递归地获得BST的高度,而是树的宽度,这会影响以后的计算。

我知道它与这个问题类似,但主要区别在于我真的尝试使用递归,其他问题使用迭代并仅称为递归。 how to find the height of a node in binary tree recursively

2 个答案:

答案 0 :(得分:2)

  1. 基本情况是递归停止的地方,你有一个:not nodenode == None

  2. 我没有看到间距问题...确保您只使用标签或仅使用空格

  3. 这确实产生了高度:沿着最长的根叶路径从根到叶的节点数。在每个节点级别,添加1,然后按照更高的子树。

    def max_height(node):
        if not node:  # this is the base case: 
            return 0  # where all recursive calls eventually stop
        left = max_height(node.left)    # <- these are the recursive calls:
        right = max_height(node.right)  # <- function x is called inside function x
        return max(left, right) + 1  # max here, not max_height
    
  4. 请注意,对于您关联的问题,这仅仅是this answer的更详细版本。

答案 1 :(得分:0)

所有回答都是正确的,但在课堂上写作时我遇到的问题很少;

所以,代码是这样的,我希望这会有所帮助。

    class Tree(object):
        def height(self, root):
            if root == None: #root == None
                return 0
            else:
                return 1 + max(self.height(root->left), self.height(root->left))
t = Tree()
t.height(t)
相关问题