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

【算法与数据结构】112、LeetCode路径总和

文章目录

  • 一、题目
  • 二、解法
  • 三、完整代码

所有的LeetCode题解索引,可以看这篇文章——【算法和数据结构】LeetCode题解。

一、题目

在这里插入图片描述
在这里插入图片描述

二、解法

  思路分析:本题通过计算根节点到叶子节点路径上节点的值之和,然后再对比目标值。利用文章【算法和数据结构】257、LeetCode二叉树的所有路径中的递归算法。这里要注意,默认路径之和是不等于目标值,一旦递归当中出现了等于的情况就直接返回,不必继续算后面的和。因此程序当中将结果result作为引用输入参数,有true出现就直接退出了。
  程序如下

class Solution {
public:          void traversal(TreeNode* root, int sumOfPath, const int targetSum, bool &result) {// 1.输入参数和返回值 sumOfPath += root->val;// 2.终止条件:遇到叶子节点if (!root->left && !root->right) {if (sumOfPath == targetSum) result = true;}// 3.单层递归逻辑:递归+回溯if (root->left && !result)  traversal(root->left, sumOfPath, targetSum, result);    // 左                         if (root->right && !result) traversal(root->right, sumOfPath, targetSum, result);  // 右}bool hasPathSum(TreeNode* root, int targetSum) {bool result = false;if(root) traversal(root, 0, targetSum, result);return result;}
};

复杂度分析:

  • 时间复杂度: O ( n ) O(n) O(n)
  • 空间复杂度: O ( n ) O(n) O(n)

三、完整代码

# include <iostream>
# include <vector>
# include <queue>
# include <string>
# include <algorithm>
# include <stack>
using namespace std;// 树节点定义
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 traversal(TreeNode* root, int sumOfPath, const int targetSum, bool &result) {// 1.输入参数和返回值 sumOfPath += root->val;// 2.终止条件:遇到叶子节点if (!root->left && !root->right) {if (sumOfPath == targetSum) result = true;}// 3.单层递归逻辑:递归+回溯if (root->left && !result)  traversal(root->left, sumOfPath, targetSum, result);    // 左                         if (root->right && !result) traversal(root->right, sumOfPath, targetSum, result);  // 右}bool hasPathSum(TreeNode* root, int targetSum) {bool result = false;if(root) traversal(root, 0, targetSum, result);return result;}
};template<typename T>
void my_print(T& v, const string msg)
{cout << msg << endl;for (class T::iterator it = v.begin(); it != v.end(); it++) {cout << *it << ' ';}cout << endl;
}template<class T1, class T2>
void my_print2(T1& v, const string str) {cout << str << endl;for (class T1::iterator vit = v.begin(); vit < v.end(); ++vit) {for (class T2::iterator it = (*vit).begin(); it < (*vit).end(); ++it) {cout << *it << ' ';}cout << endl;}
}// 前序遍历迭代法创建二叉树,每次迭代将容器首元素弹出(弹出代码还可以再优化)
void Tree_Generator(vector<string>& t, TreeNode*& node) {if (!t.size() || t[0] == "NULL") return;    // 退出条件else {node = new TreeNode(stoi(t[0].c_str()));    // 中if (t.size()) {t.assign(t.begin() + 1, t.end());Tree_Generator(t, node->left);              // 左}if (t.size()) {t.assign(t.begin() + 1, t.end());Tree_Generator(t, node->right);             // 右}}
}// 层序遍历
vector<vector<int>> levelOrder(TreeNode* root) {queue<TreeNode*> que;if (root != NULL) que.push(root);vector<vector<int>> result;while (!que.empty()) {int size = que.size();  // size必须固定, que.size()是不断变化的vector<int> vec;for (int i = 0; i < size; ++i) {TreeNode* node = que.front();que.pop();vec.push_back(node->val);if (node->left) que.push(node->left);if (node->right) que.push(node->right);}result.push_back(vec);}return result;
}// 二叉树所有路径
class Solution2 {
public:// 前序遍历递归法:精简版本      void traversal(TreeNode* root, string path, vector<string>& result) { // 1.输入参数和返回值        path += to_string(root->val);      // 中间节点先加入pathif (!root->left && !root->right) {  // 2.终止条件:遇到叶子节点result.push_back(path);return;}// 3.单层递归逻辑:递归+回溯if (root->left) traversal(root->left, path + "->", result);     // 左if (root->right) traversal(root->right, path + "->", result);   // 右}vector<string> binaryTreePaths(TreeNode* root) {vector<string> result;if (!root) return result;traversal(root, "", result);return result;}
};int main()
{vector<string> t = { "5", "4", "11", "7", "NULL", "NULL", "2", "NULL", "NULL", "NULL", "8", "13", "NULL", "NULL", "4", "NULL", "1", "NULL", "NULL"};   // 前序遍历my_print(t, "目标树");TreeNode* root = new TreeNode();Tree_Generator(t, root);vector<vector<int>> tree = levelOrder(root);my_print2<vector<vector<int>>, vector<int>>(tree, "目标树:");Solution2 s2;vector<string> path = s2.binaryTreePaths(root);my_print(path, "所有路径为:");Solution s;int targetSum = 22;bool result = s.hasPathSum(root, targetSum);cout << "路径总和是否满足目标值:  " << result << endl;system("pause");return 0;
}

end

http://www.lryc.cn/news/144134.html

相关文章:

  • ②matlab桌面和编辑器
  • 高亮img、pdf重点部分(html2canvas、pdfjs-dist、react-pdf)
  • 18.神奇导航菜单指示器
  • WPF+Prism+WebApi 学习总结
  • uniapp热更新
  • AUTOSAR从入门到精通-【应用篇】基于CAN协议的汽车尾气后处理诊断系统的软件开发(续)
  • mybatis plus新版代码生成器,类型转换处理器ITypeConvertHandler使用
  • python中的matplotlib画直方图(数据分析与可视化)
  • 【详解】文本检测OCR模型的评价指标
  • Python遥感图像处理应用篇038 GDAL 遥感图像特征提取(统计特征图)
  • 全局ID生成方式
  • c++之指针
  • JVM 访问对象的两种方式
  • yo!这里是Linux基础开发工具介绍
  • 本地组策略编辑器找不到怎么解决?| 解决windows home 版本隐藏本地组策略编辑器的问题 | 简单的介绍本地组策略编辑器
  • 将Spring boot 项目部署到tomcat服务艰难
  • 第十二章 ObjectScript - 命令
  • 在 CentOS 7 / RHEL 7 上安装 OpenSSL 1.1.x
  • 论文阅读_模型结构_LoRA
  • uniapp获取 pdf文件流 并展示
  • Linux(进程间通信)
  • Go的Gorm数据库操作错误WHERE conditions required
  • 基于java swing和mysql实现的仓库商品管理系统(源码+数据库+运行指导视频)
  • 6、css学习6(表格)
  • Ceph源码解析:PG peering
  • 解决jupyter notebook可以使用pytorch而Pycharm不能使用pytorch的问题
  • 对建造者模式理解
  • 回归预测 | MATLAB实现CSO-ELM布谷鸟算法优化极限学习机多输入单输出回归预测(多指标,多图)
  • 静态链接库和动态链接库的区别
  • 使用 python 源码搭建 conda 环境