java - 为什么我的代码超过了时间限制 (leetcode104)
问题描述
描述: 给定一棵二叉树,找到它的最大深度。最大深度是从根节点到最远叶节点的最长路径上的节点数。
这是我的解决方案
public int maxDepth(TreeNode root) {
if(root ==null ) {
return 0 ;
}
return ( maxDepth(root.left)+1) > (maxDepth(root.right)+1 ) ?
(maxDepth(root.left)+1):(maxDepth(root.right)+1);
}
但它抛出 Time Limit Exceeded
。
然后我把它改成这个,它运行良好并被接受
public int maxDepth(TreeNode root) {
if(root ==null ) {
return 0 ;
}
int left = maxDepth(root.left)+1;
int right = maxDepth(root.right) +1 ;
return left > right ? left :right ;
}
但我不认为他们有任何区别。请帮助我了解我在哪里犯了错误。谢谢你的指导,加油!
解决方案
大概有四种方法调用
(maxDepth(root.left)+1) > (maxDepth(root.right)+1 ) ?
(maxDepth(root.left)+1):(maxDepth(root.right)+1)
在这里,您调用了 4 次 maxDepth 方法,效率不高。
root.left 和 root.right 的计算是不必要的重复递归调用。尝试通过减少方法调用的数量来思考和优化您的解决方案,这将使您的代码执行得更快。
您的第二个代码片段仅涉及 2 个递归方法调用,使其成为性能更好的解决方案。
您甚至可以使用更简单的解决方案:
if (root == null) {
return 0;
}
return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
推荐阅读
- c# - 如何使用 Outlook 应用程序从其本地路径获取邮件信息并回复所有邮件
- php - 尝试使用 Laravel 构建 Telegram 机器人并收到此错误 ReplyWithKeyBoardMethod not available
- javascript - 在反应的字符串中添加一个html元素
- wordpress - Wordpress 管理页面编辑宽度
- php - 如何在 codeigniter 中使用临时表,例如更新列和获取结果?
- ms-access - MS-Access - 追加查询 - 携带 MVF
- plesk - Plesk 目录中的应用程序
- python - Python根据日期从CSV中删除行
- javascript - 自动完成以避免文本框的选项卡操作
- android - 与函数 toString("some string") 的数据绑定