LeetCode:二叉树的最大深度(Python版本)

LeetCode刷题日记

  • 二叉树的最大深度
    • Python代码

二叉树的最大深度

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/

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

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

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

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

在这里插入图片描述
返回它的最大深度 3 。

Python代码

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

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

执行用时 : 44 ms, 在Maximum Depth of Binary Tree的Python提交中击败了99.70% 的用户
内存消耗 : 14.5 MB, 在Maximum Depth of Binary Tree的Python提交中击败了35.98% 的用户

你可能感兴趣的:(Python,二叉树)