LeetCode刷题_c++版-113路径总和二

/**
 * 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:
    //先序遍历计算路径和
    void preOrderTraverse(int targetSum, TreeNode* root, vector<vector<int>>& result, int sum, vector<int> path){
    
    
        if(root == NULL) return;

        sum += root->val;
        path.push_back(root->val);
        //cout<< root->val;
        //到了叶节点,如果路径和等于目标,则放入结果集合
        if (root ->left == NULL && root->right == NULL){
    
    
            //cout<<sum<<endl;
            if(sum == targetSum){
    
    
                result.push_back(path);
            }return;
        }
        //数值有正有负,不能剪枝
        //if(targetSum >=0 && sum > targetSum) return;
       
        //递归先序变量
        preOrderTraverse(targetSum, root->left, result, sum, path);
        preOrderTraverse(targetSum, root->right, result, sum, path);
    }
    vector<vector<int>> pathSum(TreeNode* root, int targetSum) {
    
    
        vector<vector<int>> result;
        //if(root == NULL   ) return result;
        vector<int> path;
        preOrderTraverse(targetSum, root, result, 0, path);
        return result;

    }
};

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_44343355/article/details/128888871
今日推荐