113. Path Sum II
2024-10-19 06:19:25
题目:
Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.
For example:
Given the below binary tree and sum = 22
,
5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1
return
[
[5,4,11,2],
[5,8,4,5]
]
题解:
与上一题不同的是,要存储所有的root - leaf路径,所以在DFS的基础上我们还要增加backtracking。回溯的点有两个,一个是当前root满足条件,返回时,此时回溯保证当前root的sibling结果正确; 另外一个是遍历完当前root的左子树和右子树时, 这时回溯也是保证sibling结果正确。比如 root = [0, 1, 1], sum = 1,则计算完左边的1时可以正确计算到右边的1。或者 root = [0, 1, 1, 0, 0], sum = 1, 遍历完左边的两个0后可以正确计算到右边1的结果。 (有空要组织一下语言)
Time Complexity - O(n), Space Complexity - O(n)。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<List<Integer>> pathSum(TreeNode root, int sum) {
List<List<Integer>> res = new ArrayList<>();
ArrayList<Integer> list = new ArrayList<>();
dfs(res, list, root, sum);
return res;
} private void dfs(List<List<Integer>> res, ArrayList<Integer> list, TreeNode root, int sum) {
if(root == null)
return;
if(root.left == null && root.right == null && root.val == sum) {
list.add(root.val);
res.add(new ArrayList<Integer>(list));
list.remove(list.size() - 1);
return;
} list.add(root.val);
sum -= root.val;
dfs(res, list, root.left, sum);
dfs(res, list, root.right, sum);
list.remove(list.size() - 1);
}
}
二刷:
注意回溯的点。
Java:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<List<Integer>> pathSum(TreeNode root, int sum) {
List<List<Integer>> res = new ArrayList<>();
List<Integer> list = new ArrayList<>();
pathSum(res, list, root, sum);
return res;
} private void pathSum(List<List<Integer>> res, List<Integer> list, TreeNode root, int sum) {
if (root == null) return;
sum -= root.val;
list.add(root.val);
if (root.left == null && root.right == null && sum == 0) {
res.add(new ArrayList<>(list));
list.remove(list.size() - 1);
return;
}
pathSum(res, list, root.left, sum);
pathSum(res, list, root.right, sum);
list.remove(list.size() - 1);
}
}
测试:
最新文章
- Apache与Tomcat的整合
- <;-0基础学python.第一课->;
- webix源码阅读
- const放在函数前和放在函数后
- 实现jsp网页设为首页功能
- 给MyEclipse 10增加SVN功能
- function field , store={}...
- Mysql学习(慕课学习笔记8)插入、更新、删除记录
- easyui datagrid footer 页脚问题
- Python获取秒级时间戳与毫秒级时间戳
- 洛谷 P1041 错解
- 当PsychicBoom_发觉自己是个大SB的时候……
- linux开通端口允许其他机器访问
- [转]使用python爬取东方财富网机构调研数据
- nova scheduler filters 配置
- Java使用for循环输出菱形
- Android事件总线(四)源码解析otto
- Servlet基本_画面遷移
- Node.js 文件系统fs模块
- LINUX 实现端口转发 - 安装使用rinetd