leetcode437
2024-08-24 12:53:10
/**
* Definition for a binary tree node.
* public class TreeNode {
* public int val;
* public TreeNode left;
* public TreeNode right;
* public TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int PathSum(TreeNode root, int sum)
{
if (root == null)
{
return ;
}
return PathSumFrom(root, sum) + PathSum(root.left, sum) + PathSum(root.right, sum);
} private int PathSumFrom(TreeNode node, int sum)
{
if (node == null)
{
return ;
}
return (node.val == sum ? : )
+ PathSumFrom(node.left, sum - node.val) + PathSumFrom(node.right, sum - node.val);
}
}
https://leetcode.com/problems/path-sum-iii/#/description
补充一个python实现,使用递归:
class Solution:
def pathSum(self, root: 'TreeNode', sum: 'int') -> 'int':
if root == None:
return
return self.pathSumWithRoot(root,sum) + self.pathSum(root.left,sum) + self.pathSum(root.right,sum) def pathSumWithRoot(self,root,sum):
if root == None:
return
ret =
if root.val == sum:
ret +=
ret += self.pathSumWithRoot(root.left,sum-root.val) + self.pathSumWithRoot(root.right,sum-root.val)
return ret
这种实现的时间复杂度是O(n^2),执行效率比较低。
再补充一个更高效的实现,使用hash表进行缓存:(如果必须符合这个时间复杂度的要求O(n),就可以当作hard级别的题目了)
class Solution(object):
def pathSum(self, root, target):
# define global result and path
self.result =
cache = {:} # recursive to get result
self.dfs(root, target, , cache) # return result
return self.result def dfs(self, root, target, currPathSum, cache):
# exit condition
if root is None:
return
# calculate currPathSum and required oldPathSum
currPathSum += root.val
oldPathSum = currPathSum - target
# update result and cache
self.result += cache.get(oldPathSum, )
cache[currPathSum] = cache.get(currPathSum, ) + # dfs breakdown
self.dfs(root.left, target, currPathSum, cache)
self.dfs(root.right, target, currPathSum, cache)
# when move to a different branch, the currPathSum is no longer available, hence remove one.
cache[currPathSum] -=
最新文章
- IP地址的组成
- 前端构建:Less入了个门
- 后缀自动机&;序列自动机综合
- GTD时间管理(3)---行动容器分析理论法
- error LNK2005 new,delete 等已经在LIBCMT.lib(delete.obj) 中定义 错误修正
- aspx页面记住密码
- Vue + element-ui
- Caused by: java.lang.IllegalArgumentException: 'dataSource' or 'jdbcTemplate' is required
- 键盘上的";整蛊专家";,如何防止短信轰炸机
- iOS 新建xib文件时,最外层view的约束问题
- cookiejar
- hdu 4506 快速幂
- intellij与eclipse默认快捷键对比
- 使用plot_importance绘制特征重要性曲线
- ffmpeg 视频 转 gif
- java.math.*;(一)
- visual tudio 2017--发布
- python 字符串的I/O 操作
- 论坛遇到附件上传失败问题总结(discuz)
- linux Posix 信号量 二
热门文章
- Android &; iOS 启动画面工具
- .NET并行计算和并发3.2-多线程调用Invoke
- JPA问题汇总
- 多线程callable使用方法
- C程序第三次作业
- Git删除分支/恢复分支
- c语言笔记4数据的输入和输出
- leetcode 3.Longest Substring Without Repeating Charcters
- Python开发 基礎知識 3.類別&;方法 (bool &; str) (未完待續)
- 对数据进行GZIP压缩或解压缩