JAVA,Backtracking


  • 0
    	/**
    	 * @param root
    	 * @param sum
    	 * @return
    	 */
    	public List<List<Integer>> pathSum(TreeNode root, int sum) {
    		List<List<Integer>> result = new ArrayList<List<Integer>>();
    		List<Integer> currentResult = new ArrayList<Integer>();
    		dfs(root, sum, result, currentResult);
    		return result;
    	}
    
    	/**
    	 * 回溯法
    	 * 
    	 * @param node
    	 * @param sum
    	 * @param result
    	 * @param currentResult
    	 */
    	public void dfs(TreeNode node, int sum, List<List<Integer>> result, List<Integer> currentResult) {
    		if (node == null) {
    			return;
    		} else {
    			sum -= node.val;
    			currentResult.add(node.val);
    			if (node.left == null && node.right == null && sum == 0) {
    				result.add(new ArrayList<Integer>(currentResult));
    			}
    			dfs(node.left, sum, result, currentResult);
    			dfs(node.right, sum, result, currentResult);
    			currentResult.remove(currentResult.size() - 1);
    			sum += node.val;
    			return;
    		}
    	}
    

Log in to reply
 

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