Path Sum II

LeetCode #113


Description:

Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.

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

Idea:

跟path sum相比,本题是求路径本身。且要求出所有结果,左子树求到了满意结果,不能 return, 要接着求右子树。

parameter用两个vector,用pass by reference,所以one_path(记录目前的path的vector)在visit left subtree and right subtree后需要backtrack.

Code:

class Solution {
public:
    vector<vector<int>> pathSum(TreeNode* root, int sum) {
        vector<vector<int>> result;
        vector<int> one_path;

        pathSum(root, sum, one_path, result);

        return result;
    }
    void pathSum(TreeNode *root, int sum, vector<int>& one_path, vector<vector<int>>& result){
        if(root==NULL) return;

        one_path.push_back(root->val);
        if(root->left==NULL && root->right==NULL){
            if(root->val==sum) 
                result.push_back(one_path);
        }

        pathSum(root->left, sum-root->val, one_path, result);
        pathSum(root->right, sum-root->val, one_path, result);

        one_path.pop_back(); // backtracking
    }
};

results matching ""

    No results matching ""