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

深度优先搜索,和Path Sum I很相似。构建递归函数,通过参数的引用来储存递归信息。注意要恢复thisRe变量的状态。

/**
 * 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> >re;
        vector<int > thisRe;
        _pathSum(root, sum, re, thisRe);
        return re;
    }
    void _pathSum(TreeNode * root, int sum, vector<vector<int>>&re, vector<int>& thisRe){
        if(root == NULL) return ;
        if(sum - root->val == 0 && root->left == NULL && root->right == NULL){
            thisRe.push_back(root->val);
            re.push_back(thisRe);
            thisRe.pop_back();
            return ;
        }
        else{
            thisRe.push_back(root->val);
            _pathSum(root->left, sum - root->val, re, thisRe);
            _pathSum(root->right, sum - root->val, re, thisRe);
            thisRe.pop_back();
        }
    }
};

Untitled

 

Leave a comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.