leetcode113~Path Sum II
来源:互联网 发布:qq音乐mp3解析php源码 编辑:程序博客网 时间:2024/05/24 00:33
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]
]
该题是上一题的变形,leetcode绝对有bug,代码一开始提交始终过不了,检查也没错误,再次提交时竟然通过了。
注意点:res.add(new ArrayList<>(cur))这里必须要重新创建一个集合,否则cur改变的时候,res也会跟着改变,直接覆盖之前的内容,输出[[]]!
public class PathSumII { public List<List<Integer>> pathSum(TreeNode root, int sum) { List<List<Integer>> res = new ArrayList<>(); List<Integer> cur = new ArrayList<Integer>(); if(root==null) return res; helper(root,res,cur,sum); return res; } private void helper(TreeNode root, List<List<Integer>> res, List<Integer> cur, int sum) { if(root==null) return; cur.add(root.val); if(root.left==null && root.right==null && root.val==sum) { //这里必须要重新建立一个list集合 //如果直接cur,那么cur变化的时候,res也会跟着变化,直接覆盖之前的,最后输出[[]] List<Integer> newList = new ArrayList<>(cur); res.add(newList); } helper(root.left,res,cur,sum-root.val); helper(root.right,res,cur,sum-root.val); cur.remove(cur.size()-1); }}
0 0
- LeetCode113 Path Sum II
- Leetcode113. Path Sum II
- LeetCode113:Path Sum II
- LeetCode113. Path Sum II
- LeetCode113. Path Sum II
- leetcode113~Path Sum II
- LeetCode113 Path Sum II
- leetcode113. Path Sum II
- leetcode113. Path sum II
- LeetCode113. Path Sum II
- LeetCode113—Path Sum II
- LeetCode113. Path Sum II(Medium)
- LeetCode: Path Sum II
- LeetCode Path Sum II
- [Leetcode] Path Sum II
- LeetCode: Path Sum II
- Path Sum II
- [LeetCode] Path Sum II
- c++ Segmentation fault Warning
- c编写 Battle Over Cities
- JavaScript——封装输出log信息的方法
- 搜索推广记录的关键词看不到访问时长,是恶点吗?
- 抽象类(abstract)与接口(interface)的区别?
- leetcode113~Path Sum II
- MySQL数据库集群实现负载均衡的安装配置详解
- 1.分布式技术概述
- Android实现简单音乐播放器(MediaPlayer)
- c 编写Add Two Polynomials
- c++ builder 防止多个相同的子窗口同时出现
- 创建加密sqlite数据库
- js库
- c编写 Insertion or Heap Sort