题目描述
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.
要点
需要判断到叶节点,用DFS解决,递归求解。若左子树不存在则对右子树递归,若右子树不存在则对左子树递归,若左右子树都存在,则返回递归求解的较小的一个,记得加一后返回
class Solution{
public int minDepth(TreeNode root){
if(root == null){
return 0;
}
if(root.left == null){
return 1 + minDepth(root.right);
}
if(root.right == null){
return 1 + minDepth(root.left);
}
return 1 + Math.min(minDepth(root.left),minDepth(root.right));
}