打卡题目:leetcode第104题,二叉树的最大深度
    相似题目:111
    image.png


    【思路】
    使用二叉树的常用解法:递归得到左子树最大高度、右子树最大高度(如果某子树为空,那么高度为0),那么本层的高度就为两者高度最大值+1。


    【代码】

    1. # Definition for a binary tree node.
    2. # class TreeNode:
    3. # def __init__(self, x):
    4. # self.val = x
    5. # self.left = None
    6. # self.right = None
    7. class Solution:
    8. def maxDepth(self, root: TreeNode) -> int:
    9. # 节点为None,返回高度为0
    10. if not root:
    11. return 0
    12. left_depth, right_depth = 0, 0
    13. # 得到左子树高度
    14. if root.left:
    15. left_depth = self.maxDepth(root.left)
    16. # 得到右子树高度
    17. if root.right:
    18. right_depth = self.maxDepth(root.right)
    19. return max(left_depth, right_depth) + 1