二叉树根节点到叶子节点路径和为指定值的所有路径

二叉树根节点到叶子节点和为指定值的路径

http://www.nowcoder.com/questionTerminal/840dd2dc4fbd4b2199cd48f2dadf930a

先序遍历,套模版就是了,没啥可解释的。

class Solution {
public:
    /**
     *
     * @param root TreeNode类
     * @param sum int整型
     * @return int整型vector<vector<>>
     */
    vector<vector<int> > pathSum(TreeNode* root, int sum) {
        // write code here
        vector<vector<int>> res;
        if (!root) return res;
        vector<int> path;
        preOrder(root, res, path, sum, 0);
        return res;
    }

    void preOrder(TreeNode* root, vector<vector<int> > &res, vector<int> path, int sum, int current) {
        if (!root) return;
        current = current + root->val;
        path.push_back(root->val);
        if (!root->left && !root->right && sum == current) res.push_back(path);
        if (root->left) preOrder(root->left, res, path, sum ,current);
        if (root->right) preOrder(root->right, res, path, sum ,current);
    }
};
刷遍天下无敌手 文章被收录于专栏

秋招刷题历程

全部评论
好一手模板(手动狗头)
点赞 回复 分享
发布于 2021-05-07 00:21
你这个代码好像有bug
点赞 回复 分享
发布于 2021-03-27 15:59

相关推荐

04-11 23:51
门头沟学院 Java
坚定的芭乐反对画饼_许愿Offer版:人人都能过要面试干嘛,发个美团问卷填一下,明天来上班不就好了
点赞 评论 收藏
分享
评论
4
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务