113 Path Sum II

Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.
For 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]
]

Solution

/**
 * Definition for a binary tree node.
 * 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;
       if ( root == NULL ) return res;
       if ( root->left == NULL and root->right == NULL and root->val == sum ) {
           vector<int> tmp(1, root->val);
           res.push_back(tmp);
           return res;
       }
       vector<vector<int>> left = pathSum(root->left, sum - root->val);
       vector<vector<int>> right = pathSum(root->right, sum - root->val);
       int l = left.size(), r = right.size();
       for ( int i = 0; i <= l-1; i++ ) {
           vector<int> tmp = left[i];
           tmp.insert(tmp.begin(), root->val);
           res.push_back(tmp);
       }
       for ( int i = 0; i <= r-1; i++ ) {
           vector<int> tmp = right[i];
           tmp.insert(tmp.begin(), root->val);
           res.push_back(tmp);
       }
       return res;
    }
};

Notes
Insert values into a vector in c++

myvector.insert(myvector.begin() + pos, newValue);

Recursive solution: a cleaner way

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    void dfs(TreeNode* root, int sum, vector<int> curr, vector<vector<int>>& res) {
        curr.push_back(root->val);
        if ( root->left == NULL and root->right == NULL ) {
            if ( root->val != sum ) return;
            res.push_back(curr);
            return;
        }
        if ( root->left != NULL ) dfs(root->left, sum - root->val, curr, res);
        if ( root->right != NULL ) dfs(root->right, sum - root->val, curr, res);
        return;
    }
    vector<vector<int>> pathSum(TreeNode* root, int sum) {
        vector<vector<int>> res;
        vector<int> tmp;
        if ( root == NULL ) return res;
        dfs(root, sum, tmp, res);
        return res;
    }
};

results matching ""

    No results matching ""