BiruLyu
5/25/2017 - 4:46 PM

## 111. Minimum Depth of Binary Tree.java

``````# 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 not root.left:
return self.minDepth(root.right) + 1;
if not root.right:
return self.minDepth(root.left) + 1;
else:
return min(self.minDepth(root.left), self.minDepth(root.right)) + 1;

"""
TESTCASES:
Input:
[]
[1]
[1,1]
[1,null,2]
[1,2,3,null,null,1,2,1,null,null,null,1]

Output:
0
1
2
2
2
"""``````
``````/**
* Definition for a binary tree node.
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int minDepth(TreeNode root) {
if (root == null){
return 0;
} else if(root.left == null) {
return minDepth(root.right) + 1;
} else if(root.right == null) {
return minDepth(root.left) + 1;
}
return Math.min(minDepth(root.left), minDepth(root.right)) + 1;
}
}

/*
[]
[1]
[1,1]
[1,null,2]
[1,2,3,null,null,1,2,1,null,null,null,1]
*/``````