打卡题目:leetcode第104题,二叉树的最大深度
相似题目:111
【思路】
使用二叉树的常用解法:递归得到左子树最大高度、右子树最大高度(如果某子树为空,那么高度为0),那么本层的高度就为两者高度最大值+1。
【代码】
# Definition for a binary tree node.# class TreeNode:# def __init__(self, x):# self.val = x# self.left = None# self.right = Noneclass Solution:def maxDepth(self, root: TreeNode) -> int:# 节点为None,返回高度为0if not root:return 0left_depth, right_depth = 0, 0# 得到左子树高度if root.left:left_depth = self.maxDepth(root.left)# 得到右子树高度if root.right:right_depth = self.maxDepth(root.right)return max(left_depth, right_depth) + 1
