【Leetcode_总结】104. 二叉树的最大深度 - python

Q:

给定一个二叉树,找出其最大深度。

二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。

说明: 叶子节点是指没有子节点的节点。

示例:
给定二叉树 [3,9,20,null,null,15,7]

    3
   / \
  9  20
    /  \
   15   7

 


链接:https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/description/

思路:使用递归的方法,遍历二叉树的最大深度,如果树为空的话,则返回0

代码:

class Solution:
    def maxDepth(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if not root:
            return 0
        else:
            return max(self.maxDepth(root.left) + 1, self.maxDepth(root.right) + 1)

【Leetcode_总结】104. 二叉树的最大深度 - python