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
"""
'''
# non recursion
def minDepth(self, root):
if root is None:
return 0
depth = 0
stack = [root]
while stack:
next = []
depth += 1
for item in stack:
if item.left is None and item.right is None:
return depth
if item.left:
next.append(item.left)
if item.right:
next.append(item.right)
stack = next
return depth
'''
'''
def minDepth(self, root):
if root is None:
return 0
if root.left is None and root.right is None:
return 1
elif root.left and not root.right:
return self.minDepth(root.left) + 1
elif root.right and not root.left:
return self.minDepth(root.right) + 1
else:
return min(self.minDepth(root.left), self.minDepth(root.right)) + 1
'''
def minDepth(self, root):
if root is None:
return 0
left = self.minDepth(root.left)
right = self.minDepth(root.right)
if left == 0 or right == 0:
return left + right + 1
else:
return min(left, right) + 1