113. 路径总和 II


给你二叉树的根节点 root 和一个整数目标和 targetSum ,找出所有 从根节点到叶子节点 路径总和等于给定目标和的路径。

叶子节点 是指没有子节点的节点。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/path-sum-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

class Solution {

    private List> ans = new ArrayList<>();

    private LinkedList path = new LinkedList<>();

    private int target;

    private void solve(TreeNode root, int sum) {
        if (root.left == null && root.right == null) {
            if (sum == target) {
                ans.add(new ArrayList<>(path));
            }
            return;
        }

        if (root.left != null) {
            path.offerLast(root.left.val);
            solve(root.left, sum + root.left.val);
            path.pollLast();
        }

        if (root.right != null) {
            path.offerLast(root.right.val);
            solve(root.right, sum + root.right.val);
            path.pollLast();
        }
    }

    public List> pathSum(TreeNode root, int targetSum) {
        if (root == null) {
            return Collections.emptyList();
        }
        this.target = targetSum;
        this.path.offerLast(root.val);
        solve(root, root.val);
        return ans;
    }
}


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;
    }
}

相关