Friday, May 12, 2017

Binary Tree Path Sum II

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */
public class Solution {
    /**
     * @param root the root of binary tree
     * @param target an integer
     * @return all valid paths
     */
    public List<List<Integer>> binaryTreePathSum2(TreeNode root, int target) {
        // Write your code here
        List<List<Integer>> result = new ArrayList<List<Integer>>();
        if (root == null) return result;
        dfs(root, target, new ArrayList<Integer>(), result);
        return result;
    }
    private void dfs(TreeNode root, int target, List<Integer> path, List<List<Integer>> result) {
        if (root == null) return;
        path.add(root.val);
        int sum = 0;
        for (int i = path.size() - 1; i >= 0; i--) {
            sum += path.get(i);
            if (sum == target) {
                List<Integer> subResult = new ArrayList<>();
                for (int j = i; j < path.size(); j++) {
                    subResult.add(path.get(j));
                }
                result.add(subResult);
            }
        }
       
        dfs(root.left, target, path, result);
        dfs(root.right, target, path, result);
        path.remove(path.size() - 1);
    }
}

No comments:

Post a Comment