Path Sum II

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]]

分析: dfs求解即可

/**
 * 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 find(TreeNode* root, int sum,vector<int>& curPath, vector<vector<int>> & res ){
        if(root==nullptr)
            return;
        if(root->left){
            curPath.push_back(root->left->val);
            find(root->left, sum-root->val, curPath,res);
            curPath.pop_back();
        }
        if(root->right){
            curPath.push_back(root->right->val);
            find(root->right, sum-root->val,curPath,res);
            curPath.pop_back();
        }
        if(root->left==nullptr && root->right==nullptr && sum==root->val)
            res.push_back(curPath);
        
        return;
    }
    vector<vector<int>> pathSum(TreeNode* root, int sum) {
        vector<vector<int>> res;
        if(root==nullptr)
            return res;
        vector<int> curPath;
        curPath.push_back(root->val);
        find(root, sum, curPath, res);
        
        return res;
    }
};

 

posted @ 2016-11-12 20:01  WillWu  阅读(170)  评论(0编辑  收藏  举报