My java accepted solution


  • 0
    S
    the idea is  to start from a node and to try its left then right tree  to find a path
    List<Integer> tmp = new ArrayList<Integer> ();
        	List<List<Integer>> result = new ArrayList<List<Integer>>();
        	
            public List<List<Integer>> pathSum(TreeNode root, int sum) {
            	getAll (root,sum);
            	return result ;
            }
            
            private void getAll (TreeNode root, int sum){
            	if (root == null) return ;    	
            	if (root.left == null && root.right == null && sum - root.val == 0) {    		
            		tmp.add(root.val);
            		List<Integer> copy = new ArrayList<Integer> (tmp);
            		result.add(copy);
            		tmp.remove(tmp.size() - 1) ;
            	}    	
            	tmp.add(root.val);
            	//try left tree;
        		getAll (root.left, sum - root.val);
            	//try right tree;
        		getAll (root.right, sum - root.val);
        		//remove current value 
        		tmp.remove(tmp.size() - 1) ;   	    	
            }

Log in to reply
 

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