题解 | #二叉树根节点到叶子节点和为指定值的路径# C++ 解法,迷惑求助,牛客全局变量还得初始化?

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

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

题解 | #二叉树根节点到叶子节点和为指定值的路径#
C++ 解法,迷惑求助,牛客全局变量还得初始化?

/**
 * struct TreeNode {
 *    int val;
 *    struct TreeNode *left;
 *    struct TreeNode *right;
 * };
 */

class Solution {
public:
    /**
     * 
     * @param root TreeNode类 
     * @param sum int整型 
     * @return int整型vector<vector<>>
     */
    vector<vector<int> > ans;
    vector<int> path;
    int curSum = 0; // What happened? Why should I initialize the global variable? If not, defeat.
    void preOrder(TreeNode *node, int sum) {
        path.push_back(node->val);
        curSum += node->val;
        if (!node->left && !node->right && curSum == sum) ans.push_back(path);
        if (node->left) preOrder(node->left, sum);
        if (node->right) preOrder(node->right, sum);
        path.pop_back();
        curSum -= node->val;
        return ;
    }
    vector<vector<int> > pathSum(TreeNode* root, int sum) {
        if (root == nullptr) return ans;
        preOrder(root, sum);
        return ans;
    }
};
全部评论

相关推荐

点赞 评论 收藏
转发
1 收藏 评论
分享
牛客网
牛客企业服务