题解 | 二叉树中和为某一值的路径(二)

二叉树中和为某一值的路径(二)

https://www.nowcoder.com/practice/b736e784e3e34731af99065031301bca

/**
 * struct TreeNode {
 *	int val;
 *	struct TreeNode *left;
 *	struct TreeNode *right;
 *	TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 * };
 */
class Solution {
public:
    vector<vector<int>> ans;
    vector<int> path;

    void dfs(TreeNode* root, int& target, int sum) {
        path.emplace_back(root->val);

        sum += root->val;
        if (sum == target && !root->left && !root->right) ans.emplace_back(path);

        if (root->left) dfs(root->left, target, sum);
        if (root->right) dfs(root->right, target, sum);

        path.pop_back();
    }

    vector<vector<int> > FindPath(TreeNode* root, int target) {
        if (!root) return {};
        // write code here
        dfs(root, target, 0);

        return ans;
    }
};

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务