首页 > 解决方案 > 理解这个递归函数

问题描述

我得到了以下递归函数来计算二叉树的最长路径。我是递归函数的新手,有人可以帮助了解这个函数如何通过给定的示例得出结果 = 4 吗? 在此处输入图像描述

class Solution:
    def maxDepth(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if root is None:
            return 0
        else:
            lDepth = self.maxDepth(root.left)
            rDepth = self.maxDepth(root.right)

        if lDepth > rDepth:
            return lDepth+1
        else:
            return rDepth+1

标签: pythonrecursion

解决方案


如有疑问,您可以打印相应的 lDepth、rDepth、root.left、root.right。

对于这个问题,它将自上而下评估值。原谅我画得不好。lol

在此处输入图像描述


推荐阅读