Open rocksc30 opened 1 year ago
路径总和 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 {
private List<List<Integer>> ans = new ArrayList<>();
private Stack<Integer> path = new Stack<>();
private void traveral(TreeNode root, int count){
if (root.left == null && root.right == null && count == 0) {
ans.add(new ArrayList(path));
return;
}
if (root.left == null && root.right == null) {
return;
}
if (root.left != null) {
path.push(root.left.val);
traveral(root.left, count - root.left.val);
path.pop();
}
if (root.right != null) {
path.push(root.right.val);
traveral(root.right, count - root.right.val);
path.pop();
}
}
public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
if (root == null) {
return ans;
}
path.push(root.val);
traveral(root, targetSum - root.val);
return ans;
}
}