# 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):
"""
:type root: TreeNode
:rtype: int
"""
if root==None:
return 0
leftdpth=self.maxDepth(root.left)
rightdpth=self.maxDepth(root.right)
if leftdpth>=rightdpth:
return leftdpth+1
else:
return rightdpth+1
算法思想:
首先判断根结点是否存在,然后递归调用maxDepth,把下一层叶节点当做根节点,每次调用都会判断root是否存在,我们可以这样理解
leftdepth=self.maxDpeth(root.left.left.left...)
right类似,每次我们都会判断root左子叶和右子叶是否存在,leftdpth和rightdpth相当于每次递归左右子叶的计数器,最后我们取最大的那个加一(加上根结点)
ps:递归思想很重要。
本文介绍了一种求解二叉树最大深度的递归算法。通过递归地计算二叉树每个节点的左右子树深度,并返回较大值加一的方式得出整棵树的最大深度。
1154

被折叠的 条评论
为什么被折叠?



