描述
給定一個二叉樹和一個目标和,找到所有從根節點到葉子節點路徑總和等于給定目标和的路徑。
葉子節點是指沒有子節點的節點。
線上評測位址:
領扣題庫官網樣例1
輸入: root = {5,4,8,11,#,13,4,7,2,#,#,5,1}, sum = 22
5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1
輸出: [[5,4,11,2],[5,8,4,5]]
解釋:
兩條路徑之和為 22:
5 + 4 + 11 + 2 = 22
5 + 8 + 4 + 5 = 22
樣例2
輸入: root = {10,6,7,5,2,1,8,#,9}, sum = 18
10
/ \
6 7
/ \ / \
5 2 1 8
\
9
輸出: [[10,6,2],[10,7,1]]
解釋:
兩條路徑之和為 18:
10 + 6 + 2 = 18
10 + 7 + 1 = 18
當通路的節點是葉子節點的時候,建立一個清單,插入到result中,然後傳回result。 分别周遊左右子樹的節點,然後将他們分别插入到葉子節點之前。
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param root: a binary tree
* @param sum: the sum
* @return: the scheme
*/
vector<vector<int>> pathSum(TreeNode * root, int sum) {
// Write your code here.
vector<int> path;
vector<vector<int>> Spath;
int weight = 0;
findpath(Spath,root,sum,path,weight);
return Spath;
}
void findpath(vector<vector<int>> &Spath,TreeNode* root,int sum,vector<int> &path,int weight)
{
if(root == NULL){
return;
}
weight = weight + root->val;
path.push_back(root->val);
if(weight == sum && root->left == NULL && root->right == NULL)
{
Spath.push_back(path);
weight = weight - root->val;
path.pop_back();
return;
}
findpath(Spath,root->left,sum,path,weight);
findpath(Spath,root->right,sum,path,weight);
path.pop_back();
}
};
更多題解參考:
九章官網solution