Description:Given a binary tree, find its minimum depth. The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. Note: A leaf is a node with no children.
Link: 111. Minimum Depth of Binary Tree
EXamples:
Example 1:
Input: root = [3,9,20,null,null,15,7] Output: 2 Example 2: Input: root = [2,null,3,null,4,null,5,null,6] Output: 5
思路: 之前计算最深的路径时,是1+max(左子树的最深度,右子树的最深度),现在求最小深度,即最短路径的节点数,就用1+min(左子树的最小深度,右子树的最小深度)。但是看Example2, 如果没有左子树,最小深度不是1,而是右子树的最小深度5,所以要单独处理。
class Solution(object): def minDepth(self, root): """ :type root: TreeNode :rtype: int """ if not root: return 0 if not root.left: return 1 + self.minDepth(root.right) elif not root.right: return 1 + self.minDepth(root.left) else: return 1 + min(self.minDepth(root.left), self.minDepth(root.right))
日期: 2021-03-18