題目
給定一個(gè)二叉樹(shù)和一個(gè)目標(biāo)和,找到所有從根節(jié)點(diǎn)到葉子節(jié)點(diǎn)路徑總和等于給定目標(biāo)和的路徑。
說(shuō)明: 葉子節(jié)點(diǎn)是指沒(méi)有子節(jié)點(diǎn)的節(jié)點(diǎn)。
示例:
給定如下二叉樹(shù),以及目標(biāo)和 sum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1
返回:
[
[5,4,11,2],
[5,8,4,5]
]
代碼及注釋
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int>> pathSum(TreeNode* root, int sum) {
//返回的結(jié)果數(shù)組
vector<vector<int>> res;
//臨時(shí)的路徑數(shù)組
vector<int> path;
hasPathSum(res,path,root,sum);
return res;
}
/**
* 遞歸獲取路徑
**/
void hasPathSum(vector<vector<int>>& res,vector<int> path,TreeNode* root, int sum) {
if(!root)
return;
//把當(dāng)前步驟放進(jìn)臨時(shí)數(shù)組里面
path.push_back(root->val);
//如果是葉子節(jié)點(diǎn)且滿足路徑總和要求,則把此路徑放進(jìn)結(jié)果里面
if(root->val == sum && root->left==NULL && !root->right){
res.push_back(path);
return;
}
//否則,尋找左邊路徑和右邊路徑
hasPathSum(res,path,root->left,sum-root->val);
hasPathSum(res,path,root->right,sum-root->val);
}
};