3ms JAVA Solution


  • 0
    Y
    public class Solution {
        public List<List<Integer>> pathSum(TreeNode root, int sum) {
            List<List<Integer>> res = new ArrayList<List<Integer>>();
            if(root == null) 
                return res;
            getSum(res, new ArrayList<Integer>(), sum, root, 0);
            return res;
        }
        
        public void getSum(List<List<Integer>> res, List<Integer> list, int sum, TreeNode node, int cur) {
            if(node == null)
                return;
            if(sum == cur + node.val && node.left == null && node.right == null){
                list.add(node.val);
                res.add(new ArrayList<Integer>(list));
                return;
            }
            list.add(node.val);
            getSum(res, list, sum, node.left, cur + node.val);
            if(node.left != null)
                list.remove(list.size() - 1);
            getSum(res, list, sum, node.right, cur + node.val);
            if(node.right != null)
                list.remove(list.size() - 1);
        }
    }

Log in to reply
 

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