Minimum Depth of Binary Tree @ LeetCode (Python)
kitt
posted @ 2014年2月18日 17:07
in LeetCode
, 2282 阅读
左右子树只存在一个时不能返回0, 而是要沿着那个子树继续找下去。
# class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # @param root, a tree node # @return an integer def minDepth(self, root): if root == None: return 0 if root.left == None and root.right == None: return 1 if root.left == None: return self.minDepth(root.right) + 1 if root.right == None: return self.minDepth(root.left) + 1 return min(self.minDepth(root.left), self.minDepth(root.right)) + 1