您的位置:首页 > 其它

Leetcode-path-sum-ii

2016-08-02 15:27 148 查看


题目描述

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 andsum = 22,
5
/ \
4   8
/   / \
11  13  4
/  \    / \
7    2  5   1


return
[
[5,4,11,2],
[5,8,4,5]
]


* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
import java.util.*;
public class Solution {
public ArrayList<ArrayList<Integer>> pathSum(TreeNode root, int sum) {
ArrayList<ArrayList<Integer>> array = new ArrayList<ArrayList<Integer>>();
if(root == null)
return array;
ArrayList<Integer> list = new ArrayList<Integer>();
help(root, 0, sum, list, array);
return array;
}
public void help(TreeNode root, int cur, int sum, ArrayList<Integer> list, ArrayList<ArrayList<Integer>> array) {
cur += root.val;
list.add(root.val);
if(root.left == null && root.right == null) {
if(cur == sum)
array.add(new ArrayList<Integer>(list));
}
if(root.left != null) {
help(root.left, cur, sum, list, array);
}
if(root.right != null) {
help(root.right, cur, sum, list, array);
}
cur -= root.val;
list.remove(list.size()-1);
}
}
回溯、递归。不解释。因为解释太麻烦。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: