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

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

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> temp;

    vector<vector<int> > FindPath(TreeNode* root, int target) {
        dfs(root, target);
        return ans;
    }

    void dfs(TreeNode* root, int target){
        if(root == nullptr){
            return;
        }

        if(root->left == nullptr && root->right == nullptr && root->val == target){     //是叶子节点,且刚好
            temp.push_back(root->val);
            ans.push_back(temp);
            temp.pop_back();
            return;
        }

        temp.push_back(root->val);  //添加路径
        dfs(root->left, target-root->val);
        dfs(root->right, target-root->val);
        temp.pop_back();

        return;
    }
};

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

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