第一百一十三题:(很巧妙的二叉树递归)网上借鉴
1.边界情况:
根结点为空。
2.思路:
在递归途中依次加入结点值到数组path中,到达叶子结点时如果sum为0就加入这条路径path到ans自己中,当递归回到叶子结点的父节点把叶子结点从path中除去,依次类推得到结果(非常巧妙,我脑子笨时没想出来)。
class Solution {
public:
vector<vector<int>> pathSum(TreeNode* root, int sum) {
// well the thing is to remeber the paths
// use a string to remember the path? or vector?
// I will say use vector since you can push_back and pop_back
// use the same recursive algo from the easy path sum and then pass one more parameter
vector<vector<int>> ans;
vector<int> path;
if (root == NULL) return ans;
recur(ans, root, sum, path);
return ans;
}
void recur(vector<vector<int>>& ans, TreeNode* root, int sum, vector<int>& path) {
if (root -> left == NULL && root->right == NULL & (sum - root->val) == 0) {
path.push_back(root->val);
ans.push_back(path);
path.pop_back();
return;
}
path.push_back(root->val);
if (root->left) recur(ans, root->left, sum - root->val, path);
if (root->right) recur(ans, root->right, sum - root->val, path);
path.pop_back();
}
};