111. 二叉树的最小深度
难度:简单
给定一个二叉树,找出其最小深度。
最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
说明: 叶子节点是指没有子节点的节点。
代码
package cn.edu.xjtu.carlWay.tree.minDepth;
import cn.edu.xjtu.Util.TreeNode.TreeNode;
/**
* 111. 二叉树的最小深度
* 给定一个二叉树,找出其最小深度。
* <p>
* 最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
* <p>
* 说明:叶子节点是指没有子节点的节点。
* <p>
* https://leetcode-cn.com/problems/minimum-depth-of-binary-tree/
*/
public class Solution {
/**
* 递归法,
* 遍历了所有节点不太好,应该只需要遍历到第一个叶节点就行
*
* @param root
* @return
*/
public int minDepth(TreeNode root) {
int depth = helpMinDepth(root);
return depth == -1 ? 0 : depth;
}
public int helpMinDepth(TreeNode root) {
if (root == null) {
return -1;
}
int leftDepth = helpMinDepth(root.left);
int rightDepth = helpMinDepth(root.right);
int depth = 0;
if (leftDepth == -1 && rightDepth == -1) {
depth = 0;
} else if (leftDepth == -1 || rightDepth == -1) {
// max是因为有一个值为-1,这样可以直接获得最大值,或者也可以 leftDepth + rightDepth + 1 是一个效果
depth = Math.max(leftDepth, rightDepth);
} else {
// min是取二者中的较小深度
depth = Math.min(leftDepth, rightDepth);
}
return depth + 1;
}
}