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] ]
解題分析:
此題和Path Sum不太一樣,這道題是要把所有的路徑都求出來,而不只是返回一個找到與否的bool值。
要把路徑記錄下來,當一個結點的左右結點訪問完後返回時,應當把該結點剔除掉,也就是說存儲路徑的容器應當具備棧後進先出的特點,在c++中用vector也可以實現,另外還需要一個二維的向量來保存所有路徑。
代碼如下:
class Solution {
public:
vector<vector<int>> pathSum(TreeNode* root, int sum) {
vector<vector<int> > paths;
vector<int> path;
findPaths(root, sum, path, paths);
return paths;
}
private:
void findPaths(TreeNode* node, int sum, vector<int>& path, vector<vector<int> >& paths) {
if (!node) return;
path.push_back(node -> val);
if (!(node -> left) && !(node -> right) && sum == node -> val)
paths.push_back(path);
findPaths(node -> left, sum - node -> val, path, paths);
findPaths(node -> right, sum - node -> val, path, paths);
path.pop_back();
}
};