java 2ms ,easy to understand


  • 1
    T
    public class Solution {
        public List<List<Integer>> pathSum(TreeNode root, int sum) {
            List<List<Integer>> result =new ArrayList<List<Integer>>();
            findPath(new ArrayList<Integer>(),result,root,sum);
            return result;
        }
        
        private void findPath(List<Integer> list,List<List<Integer>> result,TreeNode root,int sum){
            if(root == null){
                return;
            }
            
            sum -= root.val;
            if(sum == 0 && root.left==null&&root.right==null){
                list.add(root.val);
                result.add(new ArrayList<Integer>(list));
                list.remove(list.size()-1);
                return;
            }
            list.add(root.val);
            findPath(list,result,root.left,sum);
            findPath(list,result,root.right,sum);
            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.