/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int minDepth(TreeNode root) {
if(root==null){
return 0;
}
if(root.left==null && root.right==null){
return 1;
}
if(root.left!=null&&root.right!=null){
return 1+<span style="color:#ff6666;">Math.min(minDepth(root.left), minDepth(root.right));</span>
}else if(root.left!=null){
return 1+minDepth(root.left);
}else{
return 1+minDepth(root.right);
}
}
}
在解题过程中,碰到了Time Limit Exceeded的错误,发现是由minDepth(root.left)>minDepth(root.right)?minDepth(root.right):minDepth(root.left)引起的,换成上面:Math.min(minDepth(root.left), minDepth(root.right))没有错误。
LeetCode Minimum Depth of Binary Tree
最新推荐文章于 2019-04-11 15:34:52 发布
本文介绍了一种在二叉树中寻找最小深度的有效方法,并针对原有实现进行了优化,避免了TimeLimitExceeded的问题。通过使用Math.min替代原有的三元运算符,显著提高了算法效率。


397

被折叠的 条评论
为什么被折叠?



