🌕 113. 路埄总和 II

吞䜛童子2022幎10月10日
  • algorithm
  • tree
  • backtrace
小于 1 分钟

🌕 113. 路埄总和 II

隟床: 🌕

问题描述

img_29.png


解法

/**
 * 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     ");
    }
}

蟓出

img_28.png

䞊次猖蟑于: 2022/10/10 䞋午8:43:48
莡献者: liuxianzhishou