https://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.
Code
# 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 root is None:
return 0
if root.left is None and root.right is None:
return 1
if root.left is None and root.right is not None:
return self.minDepth(root.right) + 1
if root.right is None and root.left is not None:
return self.minDepth(root.left) + 1
return min(self.minDepth(root.left), self.minDepth(root.right))+1
Idea
There are 5 conditions to consider:
- if root is None, the current depth is zero
- if both root’s left and right child are none, the current root is a leaf node which has depth 1
- if only one of root.left or root.right child is none, the depth depends on the depth of the non-none child.
- if both root.left and root.right child are not none, then the minimum depth is the min of minDepth(root.left) and minDepth(root.right) plus 1
Of course, you can take a few logical steps to further reduce lines of codes:
class Solution:
# @param root, a tree node
# @return an integer
def minDepth(self, root):
if root == None:
return 0
if root.left==None or root.right==None:
return self.minDepth(root.left)+self.minDepth(root.right)+1
return min(self.minDepth(root.right),self.minDepth(root.left))+1