【LeetCode】Path Sum II
来源:互联网 发布:短信平台的数据库设计 编辑:程序博客网 时间:2024/06/03 23:46
题目:Path Sum II
<span style="font-size:18px;">/**LeetCode Path Sum II * 给定一棵二叉树,和一个目标值,找到值相加等于目标值的所有路径的集合 * 遍历所有路径,找到值符合的 * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } * */package javaTrain;import java.util.ArrayList;import java.util.List;public class Train11 {public List<List<Integer>> pathSum(TreeNode root, int sum) { List<List<Integer>> lists = new ArrayList(); List<Integer> list = new ArrayList(); help(root,sum,lists,list); return lists; }private void help(TreeNode root,int sum,List<List<Integer>> lists,List<Integer> list){if(root == null) return;list.add(root.val);if(root.left == null && root.right == null && root.val == sum){List<Integer> newList = new ArrayList(list);lists.add(newList); //return 不能在这里返回,因为list中有这层的叶节点,因为还要找别的路径,所以的回溯到上一节点}help(root.left,sum-root.val,lists,list);help(root.right,sum-root.val,lists,list);list.remove(list.size()-1);//在这,将这层节点从list中去除}}</span>
1 0
- LeetCode: Path Sum II
- LeetCode Path Sum II
- [Leetcode] Path Sum II
- LeetCode: Path Sum II
- [LeetCode] Path Sum II
- 【leetcode】Path Sum II
- [LeetCode]Path Sum II
- [Leetcode]Path Sum II
- [leetcode]Path Sum II
- Leetcode: Path Sum II
- LeetCode-Path Sum II
- [leetcode] Path Sum II
- LeetCode - Path Sum II
- [LeetCode] Path Sum II
- Leetcode Path Sum II
- LeetCode | Path Sum II
- 【leetcode】Path Sum II
- [LeetCode] Path Sum II
- 蚂膆肀莅薁腿膆薄袃肁膁莀
- 肆蚅羂膄膅莄螅肀膄蒆羀羆
- 袆膂蒇蚄衿芈芃蒃螁芄蒂螅
- 聿莆蕿袃膁腿蒅袂袁莅莁蒈
- 袀螂莁薆羆羁芀葿蕿膀肀蒁
- 【LeetCode】Path Sum II
- 螂羅荿薈薅袁莈芇螁螇莇荿
- 莀蒇肄肁葿蝿肇膇芅薈罿膃
- 芄薇袆袄膀薇薆肀肆薆蚈袂
- 黑马程序员 C语言基础:typedef 用法
- 莂薇羇肂芁薀肂膁薄薂螅羇
- 芈蒇袈螀芇蕿蚀聿芇艿蒃羅
- 结构性模式
- 袃袀莈薈袆羆蒇蒇螈羂芃虿