Path Sum II
来源:互联网 发布:mac os x 10.12.6镜像 编辑:程序博客网 时间:2024/06/16 09:08
Problem:
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]]
Solution:
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
List<List<Integer>> result = new ArrayList<>();
List<Integer> list = new ArrayList<>();
int gsum;
public List<List<Integer>> pathSum(TreeNode root, int sum) {
if(root==null)
return result;
gsum = sum;
subSum(root, 0);
return result;
}
private void subSum(TreeNode root, int preSum)
{
if(root.left!=null)
{
list.add(root.val);
subSum(root.left, preSum+root.val);
list.remove(list.size()-1);
}
if(root.right!=null)
{
list.add(root.val);
subSum(root.right, preSum+root.val);
list.remove(list.size()-1);
}
if(root.left==null&&root.right==null)
{
if(preSum+root.val==gsum)
{
ArrayList<Integer> ls = new ArrayList<>(list);
ls.add(root.val);
result.add(ls);
}
}
}
}
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
List<List<Integer>> result = new ArrayList<>();
List<Integer> list = new ArrayList<>();
int gsum;
public List<List<Integer>> pathSum(TreeNode root, int sum) {
if(root==null)
return result;
gsum = sum;
subSum(root, 0);
return result;
}
private void subSum(TreeNode root, int preSum)
{
if(root.left!=null)
{
list.add(root.val);
subSum(root.left, preSum+root.val);
list.remove(list.size()-1);
}
if(root.right!=null)
{
list.add(root.val);
subSum(root.right, preSum+root.val);
list.remove(list.size()-1);
}
if(root.left==null&&root.right==null)
{
if(preSum+root.val==gsum)
{
ArrayList<Integer> ls = new ArrayList<>(list);
ls.add(root.val);
result.add(ls);
}
}
}
}
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
- Distinct Subsequences
- Flatten Binary Tree to Linked List
- 常用 索引 约束 查询--格式不变(插入代码-->SQL)
- Jlink无法连接电脑的解决办法
- UNP卷1:第十三章(守护进程和inetd超级服务器)
- Path Sum II
- hackxor渗透平台环境的配置与使用
- Minimum Depth of Binary Tree
- Single Number
- Balanced Binary Tree
- 。。。
- 整理、记录出来的
- Convert Sorted List to Binary Search Tree
- leetcode - Balanced Binary Tree