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

解题思路:
本题是112. Path Sum的扩展题,112. Path Sum求个数,本题求具体所有的路径,采用回朔法。

代码如下:

class Solution {
    vector<vector<int>> ret;
public:
    void pathSumHelper(TreeNode* root, vector<int> & vec, int sum) {
        if(root == NULL) return;
        vec.push_back(root->val);
        if(root->left == NULL && root->right == NULL  && sum == root->val)
            ret.push_back(vec);
        
        pathSumHelper(root->left, vec, sum-root->val);
        pathSumHelper(root->right, vec, sum-root->val);
        vec.pop_back();
        return;
    }
    vector<vector<int>> pathSum(TreeNode* root, int sum) {
        vector<int> vec;
        pathSumHelper(root,vec,sum);
        return ret;
    }
};

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容