zoukankan      html  css  js  c++  java
  • leetcode 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:
        vector<vector<int>> pathSum(TreeNode* root, int targetSum) {
            int sum=0;
            vector<vector<int>> res;   //存储最终结果
            vector<int> temp; //存储临时结果
            DFS(root,targetSum,sum,res,temp);
            return res;
        }
        void DFS(TreeNode* root,int targetSum,int sum,vector<vector<int>>& res,vector<int>& temp)
        {
            if(!root)
            {
                return;
            }
            if(!root->left && !root->right) //叶节点判断是否等值
            {
                sum+=root->val;
                if(sum==targetSum)
                {
                    temp.push_back(root->val);
                    res.push_back(temp);
                    int value=temp[temp.size()-1];//移除该结果,返回上一层
                    sum-=value;
                    temp.pop_back();
                    return;
                }
                sum-=root->val;
                return;
            }
            sum+=root->val;
            temp.push_back(root->val);
            DFS(root->left,targetSum,sum,res,temp);
            DFS(root->right,targetSum,sum,res,temp);
            sum-=root->val;
            temp.pop_back();//返回上一层
        }
    };
    每天进步一点点~
  • 相关阅读:
    MySQL--lsblk命令查看块设备
    MySQL--linux IO调度算法
    一致性哈希
    MySQL--查询表统计信息
    MySQL--区分表名大小写
    MySQL--Online DDL
    MySQL--MODIFY COLUMN和ALTER COLUMN
    MySQL--修改表字段
    MySQL--增加或修改列注释
    鼠标事件
  • 原文地址:https://www.cnblogs.com/libin123/p/14598627.html
Copyright © 2011-2022 走看看