我的解題:
先判斷該路徑是否可行,不可行就return
可行就push進vector中,進一步判斷是否是符合條件
順着進入下一個節點
切回之前(pop——back())
class Solution {
public:
vector<vector<int>> pathSum(TreeNode* root, int sum) {
vector<vector<int>> res;
vector<int> line;
func(res,line,root,sum);
return res;
}
void func(vector<vector<int>> &res,vector<int> &line,TreeNode* node,int num){
if(!node) return;
line.push_back(node->val);
if(num==node->val&&!node->left&&!node->right){
res.push_back(line);
}
func(res,line,node->left,num-node->val);
func(res,line,node->right,num-node->val);
line.pop_back();
}
};