美文网首页
[leetcode]104. Maximum Depth of

[leetcode]104. Maximum Depth of

作者: SQUA2E | 来源:发表于2019-07-24 09:52 被阅读0次

题目

Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
Note: A leaf is a node with no children.
Example:
Given binary tree [3,9,20,null,null,15,7],

    3
   / \
  9  20
      /  \
   15   7
return its depth = 3.

分析

这个题目是求二叉树的最大深度,很容易想像为 一个节点的最大深度等于子节点的最大深度+1 。用递归即可实现

代码

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

class Solution:
    def maxDepth(self, root: TreeNode) -> int:
        if not root:
            return 0  # 空节点最大深度为0
        rdepth = self.maxDepth(root.right) #左节点最大深度
        ldepth = self.maxDepth(root.left)   #右节点最大深度
        
        return max(rdepth, ldepth)+1        #每个节点最大深度= 子节点最大深度+1

相关文章

网友评论

      本文标题:[leetcode]104. Maximum Depth of

      本文链接:https://www.haomeiwen.com/subject/ilytrctx.html