java DFS solution


  • 0
    2
    /**
     * Definition for a binary tree node.
     * 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) {
            ArrayList<List<Integer>> ret = new ArrayList<List<Integer>>();
            dfs(root, ret, new ArrayList<Integer>(), 0, sum);
            return ret;
        }
        private void dfs(TreeNode t, List<List<Integer>> l, List<Integer> path, int sum, int target) {
            if (t == null) {
                return;
            }
            path.add(t.val);
            sum += t.val;
            if (t.left == null && t.right == null) {
                if (sum == target) {
                    l.add(new ArrayList<Integer>(path));
                }
            }
            dfs(t.left, l, path, sum, target);
            dfs(t.right, l, path, sum, target);
            path.remove(path.size() - 1);
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.