1、题目描述:
2、题解:
方法1:深度优先搜索DFS
写递归出口,然后递归得到左子树、右子树的深度left,right,如果其中有一个为0,就返回left+right+1;都不为0,就返回深度最小的+1
# 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:
#DFS
if not root:
return 0
left = self.minDepth(root.left)
right = self.minDepth(root.right)
return left + right + 1 if not left or not right else min(left,right) + 1
方法2:广度优先搜索BFS:
在遍历每一层时,如果遇到有个结点是叶子节点,直接返回深度res。
# 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:
#BFS
if not root:
return 0
queue = collections.deque()
queue.append(root)
res = 0
while queue:
size = len(queue)
res += 1
for i in range(size):
node = queue.popleft()
if not node.left and not node.right:
return res
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
3、复杂度分析:
方法1:
时间复杂度:O(N),N为结点的数量
空间复杂度:O(H),H为树的高度,空间复杂度主要取决于递归时栈空间的开销,最坏情况下,树呈现链状,空间复杂度为 O(N)。平均情况下树的高度与节点数的对数正相关,空间复杂度为 O(logN)。
方法2:
时间复杂度:O(N),N为结点的数量
空间复杂度:O(N)