Minimum Depth of Binary Tree
Question
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.
Tags
- Tree
- BFS
Thought
Two approaches for BFS algorithm:
- queue
- recursion
Both of the implementations are provided below.
Code
queue
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def minDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
return 0
queue = [(1, root)]
while queue:
level, ptr = queue.pop(0)
if not ptr.left and not ptr.right:
return level
if ptr.left:
queue.append((level + 1, ptr.left))
if ptr.right:
queue.append((level + 1, ptr.right))
return level
recursion
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def minDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
return 0
if root.left and root.right:
return min(self.minDepth(root.left), self.minDepth(root.right)) + 1
elif root.left:
return self.minDepth(root.left) + 1
elif root.right:
return self.minDepth(root.right) + 1
else:
return 1