给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点。
示例:
给定二叉树[3,9,20,null,null,15,7]
,3 / \ 9 20 / \ 15 7
返回它的最大深度 3 。
tips: 二叉树递归方法,当前树最大深度=max(左子树最大深度,右子树最大深度)+1,代码如下:
class Solution:
def maxDepth(self, root: TreeNode) -> int:
def dg(root):
if not root:
return 0
left_depth=dg(root.left)
right_depth=dg(root.right)
return max(left_depth,right_depth)+1
return dg(root)
方法二:层遍历,每遍历一层深度加一,代码如下:
def bfs(root):
if not root:
return 0
queue=[root]
res=0
now,last=root,root
while queue:
pop=queue.pop()
if pop.left:
queue.insert(0,pop.left)
now=pop.left
if pop.right:
queue.insert(0,pop.right)
now=pop.right
if pop==last:
last=now
res+=1
return res
return bfs(root)
给定一个二叉树,找出其最小深度。
最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
说明: 叶子节点是指没有子节点的节点。
示例:
给定二叉树 [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回它的最小深度 2.注意:
1
\
2
的最小深度为2,注意到叶子节点。故需要判断其左子树、右子树都不为None时才计算深度。
tips:相比最大深度,需要多考虑一个问题,及当前节点是否是叶子节点。若向[1,2]这样的,只有一个子节点的,需要按照有子节点的那颗子树计算深度。代码如下:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def minDepth(self, root: TreeNode) -> int:
if not root:
return 0
if not root.right and not root.left:
return 1
if not root.right or not root.left:
return max(self.minDepth(root.left),self.minDepth(root.right))+1
return min(self.minDepth(root.left),self.minDepth(root.right))+1