思路:递归调用
- 递归函数参数、返回值:返回以传入节点为根节点的二叉树的最大深度。
- 递归出口:当传入根节点为空时,返回0
- 单层递归逻辑:计算以传入节点为根节点的二叉树的左子树的最大深度,以传入节点为根节点的二叉树的右子树的最大深度,返回 1 + 二者中较大的
class Solution(object):
def maxDepth(self, root):
if root==None:
return 0
leftHeight=self.maxDepth(root.left)
rightHeight=self.maxDepth(root.right)
return 1+max(leftHeight,rightHeight)
思路:与二叉树同理
class Solution(object):
def maxDepth(self, root):
if root==None:
return 0
depth=1
for child in root.children:
depth=max(depth,1+self.maxDepth(child))
return depth