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.
这个题目的重点是如何处理最小值。应该将函数分为两部分一个是root == null 时返回0,判断不是叶子节点是返回一个极大值。
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):
# write your code here
if root is None:
return 0
return self.getDepth(root)
def getDepth(self, root):
if root is None:
return sys.maxint
if root.left is None and root.right is None:
return 1
left = self.getDepth(root.left)
right = self.getDepth(root.right)
return 1 + min(left, right)
java
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/**
* @param root: The root of binary tree.
* @return: An integer.
*/
public int minDepth(TreeNode root) {
// write your code here
if (root == null) {
return 0;
}
return getDepth(root);
}
private int getDepth(TreeNode root) {
if (root == null) {
return Integer.MAX_VALUE;
}
if (root.left == null && root.right == null) {
return 1;
}
int left = getDepth(root.left);
int right = getDepth(root.right);
int depth = 1 + Math.min(left, right);
return depth;
}
}