[leetcode] 113. Path Sum II

2017-06-11  本文已影响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;
    }
};

上一篇 下一篇

猜你喜欢

热点阅读