题目: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.
思路:递归,遇到空树返回0
遇到叶子节点或者只有一个子树节点时返回子树高度+1
遇到双子树节点时返回较小子树高度+1
代码:python
# 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
lefthigh=self.minDepth(root.left)
righthigh=self.minDepth(root.right)
if lefthigh==0 :
return righthigh+1
elif righthigh==0 :
return lefthigh+1
else :
return min(lefthigh,righthigh)+1