Path Sum的变体

早上看到一个面经题跟Path Sum很像, 给一个TreeNode root和一个target,找到一条从根节点到leaf的路径,其中每个节点和等于target。 与Path Sum不同是, Path Sum要求返回boolean,这道稍作改动返回路径。原理都一样

public class Solution {
    public List<Integer> getPathSum(TreeNode root, int target) {
        List<Integer> res = new ArrayList<>();
        if (root == null) {
            return res;
        }
        getPathSum(res, root, target);
        return res;
    }
    
    private boolean getPathSum(List<Integer> res, TreeNode root, int target) {
        if (root == null) {
            return false;
        }
        res.add(root.val);
        target -= root.val;
        if (root.left == null && root.right == null && target == 0) {
            return true;
        }
        if (getPathSum(res, root.left, target)) {
            return true;
        }
        if (getPathSum(res, root.right, target)) {
            return true;
        }
        res.remove(res.size() - 1);
        return false;
    }
}
原文地址:https://www.cnblogs.com/yrbbest/p/5285921.html