LeetCode/solutions/113. Path Sum II.md
2020-02-07 10:52:28 +08:00

1.3 KiB
Raw Blame History

113. Path Sum II

思路

给定一棵二叉树求所有根到叶子路径中和为sum的路径。
考虑用DFS遍历的时候用一维数组path记录当前经过的路径每遍历一个节点就将其加入path从这个结点返回时需要把该节点从path中移除。如果当前节点是叶子节点而且 满足和为sum即可将path加入到结果二维数组res中。
实现的时候我们可以将path和res设置成全局的免得传参。

相当于遍历一遍二叉树所以时空复杂度均为O(n)

C++

class Solution {
private:
    vector<int>path;
    vector<vector<int>>res;
    void helper(TreeNode *root, int sum){
        path.push_back(root -> val);
        sum -= root -> val;
        if((!root->left) && (!root -> right) && 0 == sum) res.push_back(path);
        else{
            if(root -> left) helper(root -> left, sum);
            if(root -> right) helper(root -> right, sum);
        }
        // 返回父节点之前要删除路径上的当前节点
        path.pop_back();
    }
public:
    vector<vector<int>> pathSum(TreeNode* root, int sum) {
        path.clear(); res.clear();
        if(root) helper(root, sum);
        return res;
    }
};