原文题目:
111. Minimum Depth of Binary Tree
读题:
求最小深度,这和求树的最大深度差不多,只不过需要注意当左子树或者右子树为空时,最小深度并不为0,而是取决于非空子树的最小深度
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def minDepth(self, root): """ :type root: TreeNode :rtype: int """ if not root: return 0 lengthL = self.minDepth(root.left) lengthR = self.minDepth(root.right) if not lengthL: return lengthR + 1 if not lengthR: return lengthL + 1 return min(lengthR,lengthL) + 1