ð 113. è·¯åŸæ»å II
2022幎10æ10æ¥
- algorithm
ð 113. è·¯åŸæ»å II
éŸåºŠ: ð
é®é¢æè¿°
解æ³
/**
* 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 {
List<List<Integer>> res = new ArrayList<>();
public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
// æè·¯ïŒ
// å溯
LinkedList<Integer> path = new LinkedList<>();
mySol(root, targetSum, path, 0);
return res;
}
private void mySol(TreeNode root, int targetSum, LinkedList<Integer> path, int preSum) {
// System.out.println("root.val: " + root.val);
// print(path);
// éåœç»æ¢æ¡ä»¶
if(root == null) {
return;
}
if(root.left == null && root.right == null) {
if(preSum + root.val == targetSum) {
path.add(root.val);
res.add(new LinkedList<>(path));
path.removeLast();
}
return;
}
// 诎æå·Šå³åæ æ¯ååšäžäžªåæ é空
if(root.left != null) {
path.addLast(root.val);
mySol(root.left, targetSum, path, preSum + root.val);
path.removeLast();
}
if(root.right != null) {
path.addLast(root.val);
mySol(root.right, targetSum, path, preSum + root.val);
path.removeLast();
}
}
private void print(LinkedList<Integer> path) {
System.out.println(" ---------- ");
for(int i : path) {
System.out.print(i + " ");
}
System.out.println(" end ");
}
}