Tuesday, February 3, 2015

LeetCode [113] Path Sum II

113. Path Sum II
Medium

Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.

Note: A leaf is a node with no children.

Example:

Given the below binary tree and sum = 22,

      5
     / \
    4   8
   /   / \
  11  13  4
 /  \    / \
7    2  5   1

Return:

[
   [5,4,11,2],
   [5,8,4,5]
]
//C++: 24ms
/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<vector<int>> pathSum(TreeNode* root, int sum) {
        vector<vector<int>> res;
        vector<int> cur;
        dfs(root, sum, res, cur, 0);
        return res;
    }
    void dfs(TreeNode* root, int sum, vector<vector<int>> &res, vector<int> cur, int sum_cur){
        if(!root) return;
        int v = root->val;
        sum_cur += v;
        cur.push_back(v);
        if(!root->left && !root->right && sum_cur==sum){res.push_back(cur); return;}
        dfs(root->left, sum, res, cur, sum_cur);
        dfs(root->right, sum, res, cur, sum_cur);
    }
};
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
//Java
class Solution {
    List<List<Integer>> ret = new ArrayList<>();
    public List<List<Integer>> pathSum(TreeNode root, int sum) {
        List<Integer> l = new ArrayList<>();
        helper(root, sum, 0, l);
        return ret;
    }
    
    void helper(TreeNode node, int sum, int cur, List<Integer> list){
        if(node == null) return;
        list.add(node.val);
        cur += node.val;
        if(cur == sum && node.left == null && node.right == null){
            ret.add(list);
        }
        List<Integer> ll = new ArrayList<>(list);
        List<Integer> lr = new ArrayList<>(list);
        helper(node.left, sum, cur, ll);
        helper(node.right, sum, cur, lr);
    }
}

No comments:

Post a Comment