Thursday, January 30, 2014

[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]
]
My Code:
 vector<vector<int> > pathSum(TreeNode *root, int sum) {
        vector<vector<int> > res;
        vector<int> path;
        if(!root) return res;
        if(!root->left && !root->right){
            if(root->val == sum){
                path.push_back(root->val);
                res.push_back(path);
                return res;
            }else{
                return res;
            }
        }else{
            if(root->left){
                vector<vector<int> > leftres = pathSum(root->left, sum - (root->val));
                for(int i = 0; i < leftres.size(); ++i){
                leftres[i].insert(leftres[i].begin(), root->val);
                res.push_back(leftres[i]);
                }
            }
            if(root->right){
                vector<vector<int> > rightres = pathSum(root->right, sum - (root->val));
                for(int i = 0; i < rightres.size(); ++i){
                    rightres[i].insert(rightres[i].begin(), root->val);
                    res.push_back(rightres[i]);
                }
            }
            return res;
        }
    }

No comments:

Post a Comment