java - 找到二叉树的最小深度
问题描述
我需要找到二叉树的最小深度。我的代码在这个测试用例上失败了:[-9, -3, 2, null, 4, 4, 0, -6, null, -5]
.
给定一棵二叉树,求其最小深度示例:
给定二叉树
[3, 9, 20, null, null, 15, 7]
,3 / \ 9 20 / \ 15 7
返回其最小深度 = 2。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int count(TreeNode root) {
if (root == null) {
return 0;
}
return 1 + Math.max(count(root.left), count(root.right));
}
public int minDepth(TreeNode root) {
int left = 0, right = 0;
if (root == null) {
return 0;
}
if (root.right == null) {
return 1 + count(root.left);
}
if (root.left == null) {
return 1 + count(root.right);
}
left = count(root.left);
right = count(root.right);
return 1 + Math.min(left, right);
}
}
- 输出 = 4
- 预期 = 3
解决方案
我相信问题在于使用 Math.max 而不是 Math.min
public int minDepth(TreeNode root)
{
if(root == null)
return 0;
return 1 + Math.min(minDepth(root.left), minDepth(root.right));
}
推荐阅读
- azure - Azure 云 - 将 Web 应用程序连接到 mysql 数据库
- ios - 在swift中使用新的Podfile时如何忽略警告?
- string - 将字符串的第 n 个元素替换为另一列中的元素
- javascript - 从多个复杂子组件中获取值的最佳方法?
- r - 向数据框添加唯一行(与相交相反)
- tsql - 需要帮助重写 T-SQL 查询以使结果显示在堆积条形图中
- arrays - 创建一个仅包含字符串中的字母的数组
- css - 如何以正确的方式在 y 轴上对齐我的 div?CSS/弹性
- machine-learning - 在没有 Spark 上下文的情况下在推理时使用 PySpark 管道模型
- python - mac上的MCP2210 DLL