题目描述
给定一个二叉树,找出其最小深度。
最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
思路
采用递归的方式。
注意
注意平凡例子的最小深度,根节点为空,以及根节点的左右子节点为空的情况。还要注意最小深度的定义。
代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class MinDepth {
public int minDepth(TreeNode root) {
if(root == null)
return 0;
if(root.left == null && root.right == null)
return 1;
int min = Integer.MAX_VALUE;
if(root.left != null)
{
min = Math.min(minDepth(root.left), min);
}
if(root.right != null)
{
min = Math.min(minDepth(root.right), min);
}
return min + 1;
}
}