题意:求二叉树路径和等于sum的所有路径。
题解:dfs即可。
class Solution {
public:
void dfs(vector<vector<int>>& ans,vector<int>& pre,int sum, int total, TreeNode* root)
{
if(root->left != NULL && root->right != NULL)
{
pre.push_back(root->left->val);
dfs(ans,pre,sum,total + root->left->val,root->left);
pre.pop_back();
pre.push_back(root->right->val);
dfs(ans,pre,sum,total + root->right->val,root->right);
pre.pop_back();
}
else if(root->right != NULL)
{
pre.push_back(root->right->val);
dfs(ans,pre,sum,total + root->right->val,root->right);
pre.pop_back();
}
else if(root->left != NULL)
{
pre.push_back(root->left->val);
dfs(ans,pre,sum,total + root->left->val,root->left);
pre.pop_back();
}
else if(total == sum)
ans.push_back(pre);
}
vector<vector<int>> pathSum(TreeNode* root, int sum) {
vector<vector<int>> ans;
vector<int> pre;
ans.clear();
pre.clear();
if(root == NULL) return ans;
pre.push_back(root->val);
dfs(ans,pre,sum,root->val,root);
return ans;
}
};