题目:
给定一个二叉树,找出其最小深度。
最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
说明:叶子节点是指没有子节点的节点。
解答:
方法一:递归
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def minDepth(self, root: TreeNode) -> int:
if not root:
return 0
if root.left and (not root.right):
return self.minDepth(root.left)+1
if (not root.left) and root.right:
return self.minDepth(root.right)+1
return min(self.minDepth(root.left),self.minDepth(root.right))+1
方法二:迭代
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def minDepth(self, root: TreeNode) -> int:
if not root:
return 0
que=[root]
res=0
while que:
res+=1
t=len(que)
for i in range(t):
cur=que.pop(0)
if (not cur.left) and (not cur.right):
return res
if cur.left:
que.append(cur.left)
if cur.right:
que.append(cur.right)
return res