[leetcode]Path Sum II

简单DFS

/**
 * Definition for binary tree
 * 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<vector<int> >& ans , vector<int>& tmp) {
        if(root == nullptr) return;
        tmp.push_back(root->val);
        if(root -> left == nullptr && root -> right == nullptr) {
            if(sum - root->val == 0) {
                ans.push_back(tmp);
            }
          //  return ;
        }
        dfs(root -> left , sum-root->val , ans , tmp);
        dfs(root -> right , sum-root->val , ans , tmp);
        tmp.pop_back();
    }
    vector<vector<int> > pathSum(TreeNode *root, int sum) {
        vector<vector<int> > ans;
        if(root == nullptr) return ans;
        vector<int> tmp;
        dfs(root , sum , ans , tmp);
        return ans;
    }
};
原文地址:https://www.cnblogs.com/x1957/p/3519857.html