剑指 Offer 34. 二叉树中和为某一值的路径

剑指 Offer 34. 二叉树中和为某一值的路径

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

思路

dfs

代码

class Solution {
    private List<List<Integer>> ans;
    public List<List<Integer>> pathSum(TreeNode root, int target) {
        ans = new ArrayList<List<Integer>>();
        if (root == null) return ans;
        List<Integer> path = new ArrayList<Integer>();
        path.add(root.val);
        dfs(root, target, root.val, path);
        return ans;
    }

    public void dfs(TreeNode root, int target, int sum, List<Integer> path) {
        if (root.left == null && root.right == null) {
            if (sum == target) {
                ans.add(new ArrayList(path));
            }
            return;
        }
        if (root.left != null) {
            path.add(root.left.val);
            dfs(root.left, target, sum + root.left.val, path);
            path.remove(path.size() - 1);
        }
        if (root.right != null) {
            path.add(root.right.val);
            dfs(root.right, target, sum + root.right.val, path);
            path.remove(path.size() - 1);
        }
    }
}
posted @ 2022-04-14 16:28  沐灵_hh  阅读(10)  评论(0编辑  收藏  举报