时间:2020-6-1
题目地址:https://leetcode-cn.com/problems/minimum-depth-of-binary-tree/
题目难度:Easy
题目描述:
给定一个二叉树,找出其最小深度。
最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
说明: 叶子节点是指没有子节点的节点。
示例:
给定二叉树 [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回它的最小深度 2.
思路1:DFS分治法用递归写起来非常快,参照104 二叉树的最大深度,对于[1,2]的测试用例执行失败,因为对题目的理解不够,题目要求最小深度是到叶子节点的最短路径,1没有到叶子节点,不算,1,2才是,因此最小深度为2。
代码段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:
if(root == None):
return 0
else:
left_depth = self.minDepth(root.left)
right_depth = self.minDepth(root.right)
if(left_depth == 0):
return right_depth + 1
elif(right_depth == 0):
return left_depth + 1
else:
return min(left_depth, right_depth) + 1
总结:
- 读题很重要,这题和104一样,归纳整理同样重要
- 大神优化过的,代码整洁多了
# 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(root == None):
return 0
left_depth = self.minDepth(root.left)
right_depth = self.minDepth(root.right)
if(root.left == None or root.right == None):
return left_depth + right_depth + 1
else:
return min(left_depth, right_depth) + 1