您的位置:首页 > 编程语言 > Java开发

LeetCode 113. Path Sum II(java)

2018-03-07 09:45 387 查看
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]
]


recursion解法,树的解法比较固定,分为base case和recursion rule,然后定好参数,在需要的时候调用自身即可。

public List<List<Integer>> pathSum(TreeNode root, int sum) {
List<List<Integer>> res = new ArrayList<>();
if (root == null) {
return res;
}
helper(res, root, new ArrayList<Integer>(), sum);
return res;
}
public void helper(List<List<Integer>> res, TreeNode root, ArrayList<Integer> path, int sum) {
//base case: leaf
if (root.left == null && root.right == null) {
if (root.val == sum) {
path.add(root.val);
res.add(new ArrayList<Integer>(path));
path.remove(path.size() - 1);
}
return;
}
//recursion rule: non-leaf
path.add(root.val);
if (root.left != null) helper(res, root.left, path, sum - root.val);
if (root.right != null) helper(res, root.right, path, sum - root.val);
path.remove(path.size() - 1);
return;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java leetcode