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();//返回上一层
        }
    };
    每天进步一点点~
  • 相关阅读:
    git学习笔记
    angular自定义指令-1
    转 三范式
    CentOS 7 安装NVIDIA驱动实现修改分辨率和扩屏功能
    acm 2034
    acm 2031
    记票统计
    acm 2020 map 逆向输出
    acm 2014
    将输入的字符一个一个读入
  • 原文地址:https://www.cnblogs.com/libin123/p/14598627.html
Copyright © 2011-2022 走看看