[LeetCode 113] 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]
]

Diffculty
Medium

Similar Problems
[LeetCode 112] Path Sum Easy [LeetCode 257] Binary Tree Paths Easy [LeetCode 437] Path Sum III Easy

Analysis

像这种要找到所有符合条件的解的集合的类型的题目,通常都需要一个临时数组来保存每一个解。而且还需要用到回溯。

Solutions
class Solution {
public:
    vector<vector<int>> pathSum(TreeNode *root, int sum) {
        vector<int> path;
        vector<vector<int>> res;
        finaPathSum(root, sum, path, res);
        return res;
    }
private:
    void finaPathSum(TreeNode *root, int sum, vector<int>& path, vector<vector<int>>& res) {
        if(root == nullptr) return;
        sum -= root->val;
        path.push_back(root->val);  // 压栈
        if(root->left == nullptr && root->right == nullptr) { // 左右子节点都为空的话,说明已经到达叶节点
            if(sum == 0) res.push_back(path);
        }
        else {
            if(root->left != nullptr) finaPathSum(root->left, sum, path, res);
            if(root->right != nullptr) finaPathSum(root->right, sum, path, res);
        }
        path.pop_back();            // 退栈
    }
};

results matching ""

    No results matching ""