113. Path Sum II

1.問題

2.想法

  • 如同112.Path sum的作法

    • pre-order

    • Recursion:

      • 每次都將sum減去自己的值, 當左子node與右子node都為NULL時, 回傳sum == root->val

      • 如果左子node不為NULL, 將左子node作為input

      • 如果右子node不為NULL, 將右子node作為input

  • 再加上ray tracking

    • 注意record作為參數時不要加&

3.程式碼

/**
 * 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) {
            return res;
        }
        vector<int> record;
        pathSum(res, record, root, sum);
        
        return res;
    }
private:
    void pathSum(vector<vector<int>>& res, vector<int> record, TreeNode* root, int sum) {
        if (!root && sum == 0) {
            res.push_back(record);
            return;
        }
        
        record.push_back(root->val);
        
        if (!root->left && !root->right && sum == root->val) {
            res.push_back(record);
            return;
        }
        
        if (root->left) {
            pathSum(res, record, root->left, sum - root->val);
        }
        
        if (root->right) {
            pathSum(res, record, root->right, sum - root->val);
        }
    }
};

4.Performance

Last updated