【代码随想录day 16】 力扣 112. 路径总和

求路径总和,明确以下几点:

  1. 从根节点遍历到叶子节点,count一路减去val,当到叶子节点count正好为0时,证明这条路径就是答案,返回true
  2. 一旦收到true就停止遍历,找到一条答案就不找其他的了
  3. 当一条路径遍历完后需要回溯,count值也应该要加回来
  4. 在第一次进入递归函数时count就要减去root的val了。
cpp 复制代码
class Solution {
public:
    bool traversal(TreeNode *node, int count)
    {
        //判断终止条件
        //1.遍历到叶子节点,count逐渐减为0
        //2.遍历到叶子节点,但count不为0
        if(node->left == NULL && node->right == NULL && count == 0)
        {
            return true;
        }
        if(node->left == NULL && node->right == NULL && count != 0)
        {
            return false;
        }
        //开始递归 左
        if(node->left)
        {
            //先减去count
            count = count - node->left->val;
            //递归
            if(traversal(node->left,count))
            {
                return true;
            }
            //回溯
            count = count + node->left->val;
        }
        //开始递归 右
        if(node->right)
        {
            //先减去count
            count = count - node->right->val;
            //递归
            if(traversal(node->right,count))
            {
                return true;
            }
            //回溯
            count = count + node->right->val;
        }
        return false;
    }
    bool hasPathSum(TreeNode* root, int targetSum) {
        if(!root) return false;
        bool result = traversal(root,targetSum-root->val);

        return result;
    }
};
相关推荐
墨染点香1 天前
LeetCode 刷题【90. 子集 II】
算法·leetcode·职场和发展
我是华为OD~HR~栗栗呀1 天前
华为od-前端面经-22届非科班
java·前端·c++·后端·python·华为od·华为
潲爺1 天前
Java IDEA学习之路:第二周课程笔记归纳
java·笔记·学习
haogexiaole1 天前
es的java调用
java·elasticsearch·jenkins
开开心心就好1 天前
PDF清晰度提升工具,让模糊文档变清晰
java·服务器·前端·python·智能手机·pdf·ocr
Chan161 天前
【 设计模式 | 创建型模式 建造者模式 】
java·spring boot·设计模式·java-ee·intellij-idea·建造者模式
汤姆yu1 天前
2025版基于springboot的校内跑腿管理系统
java·spring boot·后端
Code_LT1 天前
【算法】多榜单排序->综合排序问题
人工智能·算法
江上清风山间明月1 天前
flutter 编译报错java.util.zip.ZipException: zip END header not found
java·开发语言·flutter
Tiny番茄1 天前
146. LRU缓存
数据结构·leetcode·缓存