当前位置: 首页 > news >正文

LeetCode112 路径总和

前言

题目: 112. 路径总和
文档: 代码随想录——路径总和
编程语言: C++
解题状态: 成功解答!

思路

比较简单的一个思路是遍历所有的路径,求和后再查找目标值。但是,最好的方法是一边遍历,一边比对。

代码

方法一:遍历后再查找

/*** 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 findPath(TreeNode* node, vector<int>& path, vector<int>& res) {path.push_back(node -> val);if (node -> left == NULL && node -> right == NULL) {int sum = 0;for (int i = 0; i < path.size(); i++) {sum += path[i];}res.push_back(sum);}if (node -> left) {findPath(node -> left, path, res);path.pop_back();}if (node -> right) {findPath(node -> right, path, res);path.pop_back();}}bool hasPathSum(TreeNode* root, int targetSum) {vector<int> path;vector<int> result;if (root == NULL) return false;findPath(root, path, result);for (int i = 0; i < result.size(); i++) {if (result[i] == targetSum) {return true;}}return false;}
};

方法二:边遍历边查找

/*** 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:bool findPath(TreeNode* node, int count) {if (!node -> left && !node -> right && count == 0) return true;if (!node -> left && !node -> right) return false;if (node -> left) {count -= node -> left -> val;if (findPath(node -> left, count)) return true;count += node -> left -> val;}if (node -> right) {count -= node -> right -> val;if (findPath(node -> right, count)) return true;count += node -> right -> val;}return false;}bool hasPathSum(TreeNode* root, int targetSum) {if (root == NULL) return false;return findPath(root, targetSum - root -> val);}
};
http://www.lryc.cn/news/423963.html

相关文章:

  • TI AWR1843 毫米波雷达实物展示
  • 前端JS总结(下)之事件操作
  • 如何妙用哈希表来优化遍历查找过程?刷题感悟总结,c++实现
  • 【设计模式】漫谈设计模式
  • 第N5周:Pytorch文本分类入门
  • SpringBoot 自定义 starter
  • TDengine Invalid data format 问题定位
  • Spring Boot 使用 MongoDB 教程
  • Python办公自动化:使用openpyxl 创建与保存 Excel 工作簿
  • 【张】#11 Union 共用体
  • Xcode 在原生集成flutter项目
  • ES6的promise
  • 轻松找回:如何在PostgreSQL 16中重置忘记的数据库密码
  • EVAL长度突破限制
  • 如何判断树上一个点是否在直径上
  • docker 部署 RabbitMQ
  • 设计模式 - 过滤器模式
  • 使用 Locust 进行本地压力测试
  • 【图形学】TA之路-矩阵应用平移-旋转-大小
  • Spring 循环依赖解决方案
  • 可视化大屏:如何get到领导心目中的“科技感”?
  • 基于Python的金融数据采集与分析的设计与实现
  • 使用Sanic和SSE实现实时股票行情推送
  • redis散列若干记录
  • Java面试八股之什么是STOMP协议
  • 【自用】Python爬虫学习(一):爬虫基础与四个简单案例
  • [python]uiautomation.WindowControl函数用法
  • 学习记录第二十七天
  • servlet的执行顺序
  • Go语言 类封装和绑定方法