Minimum Depth of Binary Tree
Source
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.
Example
Given a binary tree as follow:
1
/ \
2 3
/ \
4 5
The minimum depth is 2.
Python
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
"""
@param root: The root of binary tree.
@return: An integer
"""
def minDepth(self, root):
if root is None:
return 0
l = self.minDepth(root.left)
r = self.minDepth(root.right)
if l==0:
return r+1
if r==0:
return l+1
return min(l, r)+1