一、題目
網址:路徑總和 II。
難度:中等。
給定一個二叉樹和一個目標和,找到所有從根節點到葉子節點路徑總和等於給定目標和的路徑。
說明: 葉子節點是指沒有子節點的節點。
示例:
給定如下二叉樹,以及目標和 sum = 22,
示例 1:
5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1
返回:
[
[5,4,11,2],
[5,8,4,5]
]
二、程序
思路:將根節點到葉子節點的路徑path保存下來,並計算根節點到葉子節點路徑的和path_value,如果path_value==sum,則保留該路徑path。
/**
* 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) {
vector<vector<int>> res;
vector<int> path;
int path_value=0;
preOrder(root,path_value,sum,path,res);
return res;
}
private:
void preOrder(TreeNode* root,int path_value,int sum,vector<int> path,vector<vector<int>> &res)
{
if(root==NULL) return;
path_value+=root->val;
path.push_back(root->val);
if(!root->left&&!root->right&&path_value==sum)
{
res.push_back(path);
}
preOrder(root->left,path_value,sum,path,res);
preOrder(root->right,path_value,sum,path,res);
path_value-=root->val;
path.pop_back();
}
};
結果: