给定一个二叉树,找出其最大深度。二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点。
示例:
给定二叉树 [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回它的最大深度 3 。
- 层次遍历法 :使用层次遍历来统计共遍历的层次总数,因此只要某层包含节点,层次遍历就可进行,最后层次的总数就是树的深度。
class Solution:
def maxDepth(self, root: TreeNode) -> int:
if root == None:
return 0
queue = [root]
index = 0
while queue:
nextLayer = []
for node in queue:
if node.left:
nextLayer.append(node.left)
if node.right:
nextLayer.append(node.right)
index += 1
queue = nextLayer
return index
- 逐路统计法 :依次统计所有可能数的路径的长度,并使用
maxDepth
保存当前的最大深度。当访问玩所有可能的路径后,返回maxDepth
表示的树的深度。
class Solution:
def maxDepth(self, root: TreeNode) -> int:
def dfs(root, depth = 0):
global maxDepth
if root:
depth += 1
isLeaf = None
if root.left == None and root.right == None:
isLeaf = True
if root.left:
dfs(root.left, depth)
if root.right:
dfs(root.right, depth)
if isLeaf and depth > maxDepth:
maxDepth = depth
if root == None: return 0
global maxDepth
maxDepth = 0
dfs(root)
return maxDepth
- 递归法:
class Solution:
def maxDepth(self, root: TreeNode) -> int:
if root == None:
return 0
leftDepth = self.maxDepth(root.left)
rightDepth = self.maxDepth(root.right)
return max(leftDepth, rightDepth) + 1