Java DFS solution


  • 0
    J
       List<List<Integer>> result = new ArrayList<List<Integer>>();
        public List<List<Integer>> pathSum(TreeNode root, int sum) {
            if(root == null) return new ArrayList<List<Integer>>();
            helper(root,sum,new ArrayList<Integer>());
            return result;
        }
        public void helper(TreeNode node, int sum, List<Integer> cb){
            sum = sum - node.val;
            if(sum != 0 && node.left == null && node.right == null) return;
            List<Integer> comb = new ArrayList<Integer>(cb);
            comb.add(node.val);
            if(sum == 0 && node.left == null && node.right == null){ 
                result.add(comb);
                return;
            }
            if(node.left != null) helper(node.left,sum,comb);
            if(node.right != null) helper(node.right,sum,comb);
        }

Log in to reply
 

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