Path Sum II

来源:互联网 发布:孕妇必知的民间禁忌 编辑:程序博客网 时间:2024/06/15 11:54
/** * Definition for binary tree * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    public List<List<Integer>> pathSum(TreeNode root, int sum) {        List<List<Integer>> result = new ArrayList<List<Integer>>();        if (root != null){            pathSumHelper(root, sum, result, new ArrayList<Integer>());        }        return result;    }        public void pathSumHelper(TreeNode root, int sum, List<List<Integer>> result, List<Integer> path){        if (root == null) return;        path.add(root.val);        if (root.val == sum && root.left == null && root.right == null){            result.add(path);        }else{            pathSumHelper(root.left, sum-root.val, result, new ArrayList<Integer>(path));            pathSumHelper(root.right, sum-root.val, result, new ArrayList<Integer>(path));        }    }}

0 0
原创粉丝点击