首页 > 其他分享 >112. Path Sum

112. Path Sum

时间:2024-10-08 17:22:45浏览次数:3  
标签:count right return val Sum 112 Path root left

Given the root of a binary tree and an integer targetSum, return true if the tree has a root-to-leaf path such that adding up all the values along the path equals targetSum.

A leaf is a node with no children.

Example 1:

Input: root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22
Output: true
Explanation: The root-to-leaf path with the target sum is shown.

Example 2:

Input: root = [1,2,3], targetSum = 5
Output: false
Explanation: There two root-to-leaf paths in the tree:
(1 --> 2): The sum is 3.
(1 --> 3): The sum is 4.
There is no root-to-leaf path with sum = 5.

Example 3:

Input: root = [], targetSum = 0
Output: false
Explanation: Since the tree is empty, there are no root-to-leaf paths.

Constraints:

  • The number of nodes in the tree is in the range [0, 5000].
  • -1000 <= Node.val <= 1000
  • -1000 <= targetSum <= 1000

法一:深度优先搜索

class Solution {
private:
    bool traversal(TreeNode*root,int count){
        if(root->left==NULL && root->right==NULL && count==0)return true;
        if(root->left==NULL && root->right==NULL)return false;

        if(root->left){
            count-=root->left->val;
            if(traversal(root->left,count))return true;
            count+=root->left->val;
        }
        if(root->right){
            count-=root->right->val;
            if(traversal(root->right,count))return true;
            count+=root->right->val;
        }
        return false;
    }
public:
    bool hasPathSum(TreeNode* root, int targetSum) {
        if(root==NULL)return false;
        return traversal(root,targetSum-root->val);
    }
};

注意:

1,前提条件:

1)binary Tree

2)求一条路径的targetSum

2,解题流程:

1)法一:深度优先搜索:

  • 每一步的含义
    • 首先private中构造一个函数teaversal
      • 深度优先搜索也是递归,递归三部曲
        • ①确定函数类型是bool、void还是其他,以及函数的参数传递
          1. 如果需要搜索整棵树,但是不需要对返回值进行处理的话,就不需要返回值(113题)
          2. 如果需要搜索整棵树,也需要处理返回值,就需要返回值(236题)
          3. 如果需要搜索其中一条符合条件的路径,那么也需要返回值,返回值类型为bool(本题)
        • ②确定终止条件
          • 终止条件就是遇到叶节点,而且刚好得到了目标值,关于目标值,这里并没有像以前一样累加,判断是否相等,而是用count-的方式,当遇到叶节点&&count==0的时候终止,返回true
        • ③确定单层递归的逻辑
          • 当left、right不为空时进行递归
          • 注意这里有用到回溯,所以在递归之前count先-,递归玩需要判断是否已经返回了true,如果是,那就返回true,如果false,那就count加上减去的值
      • 最后不要忘了返回false,这是没有返回true的时候
    • 最后就是public中的主函数了
      • 先判断root,空就false
      • 直接return traversal(root,targetSum-root->val);

  • 知识点套路
    1. 深度优先搜索
    2. 不再用累加的方式来判断是否符合了,而是使用count-的方式,因为累加的话很难判断和回溯
  • 前提
  • 注意点
    • 单层递归后需要判断是否已经返回了false,是的话要加回去,已经true的话就可以直接返回最终结果了
    • 最后整个函数的末尾需要返回一个false,因为如果到了最后还没有返回的话,肯定是false,并且函数式bool类型,必须要有返回值

法二:迭代

class Solution {
public:
    bool hasPathSum(TreeNode* root, int targetSum) {
        if(root==NULL)return false;
        stack<pair<TreeNode*,int>>stk;
        stk.push(pair<TreeNode*,int>(root,root->val));
        while(!stk.empty()){
            pair<TreeNode*,int>node=stk.top();
            stk.pop();

            if(node.first->left==NULL && node.first->right==NULL && targetSum==node.second)return true;

            if(node.first->right){
                stk.push(pair<TreeNode*,int>(node.first->right,node.second+node.first->right->val));
            }
            if(node.first->left){
                stk.push(pair<TreeNode*,int>(node.first->left,node.second+node.first->left->val));
            }
        }
        return false;
    }
};

注意:

和之前的迭代法差不多,最需要注意的就是这里的stack里面用了pair,注意写法加上.first什么的。

113. Path Sum II

class Solution {
private:
    vector<vector<int>>result;
    vector<int>path;
    void traversal(TreeNode*root,int count){
        if(root->left==NULL && root->right==NULL && count==0){
            result.push_back(path);
            return;
        }
        if(root->left==NULL && root->right==NULL)return;

        if(root->left){
            path.push_back(root->left->val);
            count-=root->left->val;
            traversal(root->left,count);
            count+=root->left->val;
            path.pop_back();
        }
        if(root->right){
            path.push_back(root->right->val);
            count-=root->right->val;
            traversal(root->right,count);
            count+=root->right->val;
            path.pop_back();
        }
        return;
    }
public:
    vector<vector<int>> pathSum(TreeNode* root, int targetSum) {
        result.clear();
        path.clear();
        if(root==NULL)return result;
        path.push_back(root->val);
        traversal(root,targetSum-root->val);
        return result;
    }
};

标签:count,right,return,val,Sum,112,Path,root,left
From: https://blog.csdn.net/2301_80161204/article/details/142762584

相关文章

  • LeetCode 209 Minimum Size Subarray Sum 题目解析和python代码
    题目:Givenanarrayofpositiveintegersnumsandapositiveintegertarget,returntheminimallengthofasubarraywhosesumisgreaterthanorequaltotarget.Ifthereisnosuchsubarray,return0instead.Example1:Input:target=7,nums=[2,3,......
  • [论文阅读报告] Fast 2-Approximate All-Pairs Shortest Paths, SODA '24
    本篇文章介绍\(\tildeO(n^{2.032})\)的无向无权图全源最短路stretch2近似算法和\(\tildeO(n^{\frac94})\)的组合算法,以及\(\tildeO(n^{2.214}(1/\epsilon)^{O(1)}\logW)\)的非负整数边权stretch\((2+\epsilon)\)近似算法。其中\((1/\epsilon)^{O(1)}\)......
  • [ARC112F] Die Siedler 题解
    智慧题。思路考虑第二种操作。我们会想到,我们可以先把所有牌转化成第一种牌。即:\[one=\sum_{i=1}^n\prod_{j=1}^i2^{j-1}(j-1)!c_i\]这就是第一种牌的数量。然后考虑,我们可以将第一种牌转化为第一种牌,花费的代价为:\[g=(\prod_{i=1}^n2^{i-1}(i-1)!)-1\]相当于对\(g\)......
  • ubuntu更新报错Hash Sum mismatch
    查了一圈,应该是FW的问题,/etc/apt/sources.list更换成清华的源就可以了(阿里不行):debhttps://mirrors.tuna.tsinghua.edu.cn/ubuntu/jammymainrestricteduniversemultiversedeb-srchttps://mirrors.tuna.tsinghua.edu.cn/ubuntu/jammymainrestricteduniversem......
  • GESP等级考试 20241006_121124
    官网CCF-GESP编程能力等级认证https://gesp.ccf.org.cn/考钢图形化1579692243025952.pdfhttps://gesp.ccf.org.cn/101/attach/1579692243025952.pdf考钢C++1579675000242208.pdfhttps://gesp.ccf.org.cn/101/attach/1579675000242208.pdf考级相关真题解析-CCF-GESP编程......
  • [论文阅读报告] All pairs shortest paths using bridging sets and rectangular matr
    本篇文章介绍整数边权下\((\min,+)\)矩阵乘、APSP等问题的一些做法。若每个元素的权值在\([-M,M]\cap\mathbbZ\)中,\(n\timesn^r\)和\(n^r\timesn\)的\((\min,+)\)矩阵乘可做到\(\tildeO(Mn^{\omega(r)})\);有向图APSP可做到\(\tildeO(n^{2+\mu(t)})\),......
  • 2017中国大学生程序设计竞赛 - 女生专场(SDKD 2024 Summer Training Contest K2)
    A-AutomaticJudge题意\(n\)个问题,\(m\)条记录,每条记录有题号、时间、状态,第一次\(AC\)的时候计入罚时,其他没发罚\(20\)分钟。求队伍过题数和罚时。思路模拟。代码点击查看代码#include<bits/stdc++.h>usingnamespacestd;#defineintlonglongvoidsolve()......
  • CSCI1120 Introduction to Computing Using C++
    CSCI1120IntroductiontoComputingUsingC++,Fall2024/25DepartmentofComputerScienceandEngineering,TheChineseUniversityofHongKongCopyright©2024CSE,CUHKPage1of8Assignment2:GumballMachinesDue:23:59,Thu3Oct2024Filename:gumball.......
  • 题解 CF1785D - Range = √Sum
    link\(\texttt{Describe}\)构造有\(n\)个数的序列,满足以下条件:\(\foralli\in[1,n]\)并且\(1\lea_i\le10^9\)。对于任何的\(1\lei,j\len(i\nej)\),\(a_i\nea_j\)。\((\max_{i=1}^{n}a_i-\min_{i=1}^{n}a_i)^2=\sum_{i=1}^{n}a_i\)。......
  • 题解:P11129 【MX-X5-T1】「GFOI Round 1」Inverted World
    题目要求:\((a_l+\cdots+a_r)\div(r-l+1)\)是整数。即\(\frac{(a_l+a_r)\cdot(r-l+1)\div2}{r-l+1}\)为整数。即\(\frac{(a_l+a_r)}{2}\)为整数。即\(a_l+a_r\)为偶数。即\(m+(l-1)\cdotd+m+(r-1)\cdotd\)为偶数。即\(2m+(l+r-2)\cdotd\)为偶......