首页 > 其他 > 详细

Path Sum的变体

时间:2016-03-17 07:04:18      阅读:186      评论:0      收藏:0      [点我收藏+]

早上看到一个面经题跟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的变体

原文:http://www.cnblogs.com/yrbbest/p/5285921.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!