leetcode_深度搜索和广度搜索 104. 二叉树的最大深度

104. 二叉树的最大深度

  • 二叉树的最大深度是指从根节点到最远叶子节点的最长路径上的节点数。
 # Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution(object):
    def maxDepth(self, root):
        """
        :type root: Optional[TreeNode]
        :rtype: int
        """
        if not root:
            return 0
        return max(self.maxDepth(root.left), self.maxDepth(root.right)) + 1

执行过程

  • 例如有二叉树如下

         1
        / \
       2   3
      / \   
     4   5
    
  • 调用 maxDepth(root) 后:

    1. maxDepth(1):
    • 计算 maxDepth(2) 和 maxDepth(3)
    1. maxDepth(2):
    • 计算 maxDepth(4) 和 maxDepth(5)
    1. maxDepth(4):
    • root.left = None,root.right = None
      返回 0 + 1 = 1
    1. maxDepth(5):
    • root.left = None,root.right = None
      返回 0 + 1 = 1
    1. maxDepth(2):
    • max(1, 1) + 1 = 2
    1. maxDepth(3):
    • root.left = None,root.right = None
      返回 0 + 1 = 1
    1. maxDepth(1):
    • max(2, 1) + 1 = 3
      最终返回结果 3(即最大深度)
  • 时间复杂度: O(n), n为节点个数

  • 空间复杂度: O(h), h为树的高度

你可能感兴趣的:(leetcode,算法,职场和发展)