【LeetCode】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.
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]
]

前の問題112.Path Sumは、ルートノードからリーフノードへのパスがあるかどうかを判断し、加算がsumに等しいようにします.この問題では、すべてのルートノードからリーフノードに加算されたパスとsumに加算されたパスのノード値を格納して返す必要があります.
/**
 * 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> pathSum(TreeNode* root, int sum) {
        vector> result;
        vector tem;
        pathNum(root,sum,tem,result);
        return result;
    }
    void pathNum(TreeNode* root, int sum,vector tem,vector>& result){
        if(root==NULL) return;
        if(root->left==NULL && root->right==NULL){
            if(root->val==sum){
                tem.push_back(root->val);
                result.push_back(tem);
            }
            else return;
        }
        sum = sum - root->val;
        
        tem.push_back(root->val);
        pathNum(root->left,sum,tem,result);
        pathNum(root->right,sum,tem,result);
        //myself
    }
};