Path Sum II
来源:互联网 发布:高斯滤波器的算法 编辑:程序博客网 时间:2024/06/05 02:18
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]
]
先记录每条路径,若碰到叶子切点,且路径之和恰好等于sum,则记录该路径,递归回退时回退该路径。
public class Solution { List<List<Integer>> treeList = new ArrayList<List<Integer>>(); public void pathSumRe(TreeNode root, int sum,List<Integer> list) { if(root == null) { return; } int value = root.val; list.add(value); if((root.right ==null) && (root.left == null) && (value == sum))//叶子节点 { treeList.add(new ArrayList<Integer>(list)); } pathSumRe(root.right, (sum - value), list) ; pathSumRe(root.left, (sum - value), list); list.remove(list.size() - 1); } public List<List<Integer>> pathSum(TreeNode root, int sum) { List<Integer> list = new ArrayList<Integer>(); pathSumRe(root, sum,list); return treeList; }}
0 0
- LeetCode: Path Sum II
- LeetCode Path Sum II
- [Leetcode] Path Sum II
- LeetCode: Path Sum II
- Path Sum II
- [LeetCode] Path Sum II
- 【leetcode】Path Sum II
- [113]Path Sum II
- Path Sum II
- Path Sum II
- [LeetCode]Path Sum II
- Path Sum II
- Path Sum II
- [Leetcode]Path Sum II
- [leetcode]Path Sum II
- Path Sum II
- Leetcode: Path Sum II
- Path Sum II
- codeforces C. NP-Hard Problem 二分图的判定
- uLua+SimpleFramework常见问题的解答及学习笔记
- C语言文件操作详解
- 2016夏季练习——dp
- stm32 移植rt_thread
- Path Sum II
- 高并发网站更新数据库数据比较高效的方式
- leetcode_c++:哈希:Top K Frequent Elements(347)
- 孕前的第一次身体检查
- SQL版本说明
- orblsam2-理论基础(三)
- uvm_do_with注意事項
- 安装VS2015出现的bug
- java加载properties文件的六种基本方式