[LeetCode]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 binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
private:
    vector<vector<int> > ret;
public:
    void DFS(TreeNode *root,int sum,int total,vector<int> &ans)
    {
        if(root)
        {
            total+=root->val;
            ans.push_back(root->val);
            if(total==sum&&!root->left&&!root->right)
            {
                ret.push_back(ans);
            }
            
            DFS(root->left,sum,total,ans);
            ans.pop_back();
            DFS(root->right,sum,total,ans);
            ans.pop_back();
        }
        else ans.push_back(0);
    }
    vector<vector<int> > pathSum(TreeNode *root, int sum) {
        ret.clear();
        vector<int> ans;
        DFS(root,sum,0,ans);
        return ret;
    }
};

  

posted @ 2013-12-05 12:10  七年之后  阅读(175)  评论(0编辑  收藏  举报