美文网首页
[leetcode] 113. Path Sum II

[leetcode] 113. Path Sum II

作者: 叶孤陈 | 来源:发表于2017-06-11 16:29 被阅读0次

    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;
        }
    };
    
    

    相关文章

      网友评论

          本文标题:[leetcode] 113. Path Sum II

          本文链接:https://www.haomeiwen.com/subject/eaihqxtx.html