原題地址:http://oj.leetcode.com/problems/minimum-depth-of-binary-tree/
題意:
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.
解題思路:分幾種情況考慮:1,樹為空,則為0。 2,根節點如果只存在左子樹或者只存在右子樹,則返回值應為左子樹或者右子樹的(最小深度+1)。 3,如果根節點的左子樹和右子樹都存在,則返回值為(左右子樹的最小深度的較小值+1)。
代碼:
# Definition for a binary tree node # 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 self.minDepth( root.right ) + 1 if root.left != None and root.right == None: return self.minDepth( root.left ) + 1 return min( self.minDepth( root.left ), self.minDepth( root.right ) ) + 1