题目地址
https://leetcode.com/problems/path-sum-ii/description/
题目描述
113. Path Sum II
Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.
Note: A leaf is a node with no children.
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]
]
思路
dfs. 恢复现场.
关键点
- 注意, 即使是加入到res里的path也需要恢复现场, 因为后续可能继续dfs.
代码
- 语言支持:Java
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<List<Integer>> pathSum(TreeNode root, int sum) {
List<Integer> path = new ArrayList<>();
List<List<Integer>> result = new ArrayList<>();
helper(root, sum, path, result);
return result;
}
private void helper(TreeNode root, int sum, List<Integer> path,
List<List<Integer>> result) {
if (root == null) {
return;
}
path.add(root.val);
if (sum == root.val && root.left == null && root.right == null) {
result.add(new ArrayList<>(path));
} else {
helper(root.left, sum - root.val, path, result);
helper(root.right, sum - root.val, path, result);
}
path.remove(path.size() - 1);
}
}
网友评论