【LeetCode113】-路径总和

实现思路

对树进行前序遍历,在遍历过程中,保存路径和累加和,当遍历到根结点时也就是左右结点为nullptr的点时,判断加上该结点的sum是否和targetNum相等,如果相等将路径保存到结果的vector中

实现代码

/**
 * 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 solve(TreeNode* root,vector<int> path,int sum,int target,vector<vector<int>> &re){
    
    
        if(root==nullptr) return;
        if(root->left==nullptr&&root->right==nullptr){
    
    
            sum+=root->val;
            path.push_back(root->val);
            if(sum==target)
            {
    
    
                re.push_back(path);
            }
            return;
        }
        sum+=root->val;
        path.push_back(root->val);
        solve(root->left,path,sum,target,re);
        solve(root->right,path,sum,target,re);
        
    }
    vector<vector<int>> pathSum(TreeNode* root, int targetSum) {
    
    
        vector<vector<int>> re;
        vector<int> path;
        solve(root,path,0,targetSum,re);
        return re;
    }
};

需要掌握的代码:

#include < algorithm >
vector< int >path=[3,4,1,2];
reverse(path.begin(),path.end());

提交结果及分析

在这里插入图片描述

时间复杂度
O(n)

猜你喜欢

转载自blog.csdn.net/weixin_44944046/article/details/114287539