0
点赞
收藏
分享

微信扫一扫

剑指 Offer 34. 二叉树中和为某一值的路径

先序遍历+记录路径

这里少用一个变量用于记录节点和:target-root->val==0&&root->left==null&&root->right==null时,记录路径。

与遍历不同的是:需要恢复路径,即在访问完当前节点后,path需要pop最后的节点。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<vector<int>> res;
    vector<int>temp;

 
    void dfs(TreeNode*root,int target){

        if(root==nullptr) return;
        target-=root->val;
        
        temp.push_back(root->val);
        if(target==0&&root->left==nullptr&&root->right==nullptr) res.push_back(vector<int>(temp));
        dfs(root->left,target);
        dfs(root->right,target);

        target+=root->val;
        temp.pop_back();
 
    }
    vector<vector<int>> pathSum(TreeNode* root, int target) {
        dfs(root,target);
        return res;
    }
};
举报

相关推荐

0 条评论