Path Sum的变体

Posted YRB

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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;
    }
}

 

以上是关于Path Sum的变体的主要内容,如果未能解决你的问题,请参考以下文章