[LeetCode] Path Sum II
来源:互联网 发布:淘宝助理天猫版界面 编辑:程序博客网 时间:2024/06/06 14:29
Total Accepted: 10147 Total Submissions: 37132
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]]
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */public class Solution { public ArrayList<ArrayList<Integer>> pathSum(TreeNode root, int sum) { ArrayList<ArrayList<Integer>> list = new ArrayList<ArrayList<Integer>>(); ArrayList<Integer> path = new ArrayList<Integer>(); traverse(list, path, root, 0, sum); return list; } public void traverse(ArrayList<ArrayList<Integer>> list, ArrayList<Integer> path, TreeNode root, int sum, int target) { if (root == null) return; path.add(root.val); sum += root.val; if (sum == target && root.left == null && root.right == null) list.add(new ArrayList<Integer>(path)); traverse(list, path, root.left, sum, target); traverse(list, path, root.right, sum, target); path.remove(path.size() - 1); }}
0 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
- Ubuntu Gnome下怎样修改应用的图标icon
- JavaScript自定义事件
- IOS布局笔记一(代码实现自动布局)
- linux添加开机自启动脚本示例详解
- 语法笔记
- [LeetCode] Path Sum II
- 把手机变成鼠标和触摸板实现思路
- windows内核情景分析
- ubuntu下安装eclipse for C++,OPENCV
- eclipse 自动生成hbm文件
- 开发与研发:区别很大
- C++ set的insert,结构体的操作符重载需要面面俱到
- SSH端口转发
- PHP5中实现多态的两种方法实例分享投