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]
]
/**
 * Definition for binary tree
 * 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>> result;
        vector<int> v;
        genPath(result,v,0,sum,root);
        return result;
    }
    void genPath(vector<vector<int>>&result,vector<int>& v,int dep,int sum,TreeNode* root)
    {
        if(root==NULL) return;
        if(root->left==NULL && root->right==NULL)
        {
            if(sum==root->val)
            {
                vector<int> newv;
                for(int i=0;i<dep;i++)
                    newv.push_back(v[i]);
                newv.push_back(root->val);
                result.push_back(newv);
            }
            return;
        }
        if(v.size()>dep) v[dep]=root->val;
            else v.push_back(root->val);
        genPath(result,v,dep+1,sum-root->val,root->left);
        genPath(result,v,dep+1,sum-root->val,root->right);
    }
};

 

posted @ 2014-05-30 01:21  erictanghu  阅读(141)  评论(0编辑  收藏  举报