【算法与数据结构】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.hqwc.cn/news/90014.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

【拾枝杂谈】从游戏开发的角度来谈谈原神4.0更新

君兮_的个人主页 勤时当勉励 岁月不待人 C/C 游戏开发 Hello,米娜桑们&#xff0c;这里是君兮_&#xff0c;结合最近的学习内容和以后自己的目标&#xff0c;今天又开了杂谈这个新坑&#xff0c;分享一下我在学习游戏开发的成长和自己的游戏理解&#xff0c;当然现在还是一枚…

Docker容器学习:Dockerfile制作Web应用系统nginx镜像

目录 编写Dockerfile 1.文件内容需求&#xff1a; 2.编写Dockerfile&#xff1a; 3.开始构建镜像 4.现在我们运行一个容器&#xff0c;查看我们的网页是否可访问 推送镜像到私有仓库 1.把要上传的镜像打上合适的标签 2.登录harbor仓库 3.上传镜像 编写Dockerfile 1.文…

前端自学总结

文章目录 一、nodejs1.1、npm配置命令别名 二、JavaScript2.1、javascript注释 一、nodejs 1.1、npm配置命令别名 我们可以使用“node index.js”的方式运行代码 也可以利用npm配置别名的方式运行代码 在package.json中配置别名&#xff0c;利用“npm run 别名”也可以运行 st…

[Android]JNI的基础知识

目录 1.什么是JNI 2.配置JNI开发环境NDK 3.创建Native C类型的项目 4. 了解CMakeLists.txt 文件 5.了解native-lib.cpp 文件 6.在 Android 的 MainActivity 中调用 native-lib.cpp 中实现的本地方法 1.什么是JNI JNI&#xff08;Java Native Interface&#xff09;是一…

【ES】Elasticsearch 常见的简单查询

查看es中有哪些索引 请求方式&#xff1a;GET 请求地址&#xff1a;http://localhost:9200 /_cat/indices?v 参数&#xff1a;无 结果&#xff1a; 查看索引全部数据 请求方式&#xff1a;GET 请求地址&#xff1a;http://localhost:9200/index-2023-08/_search 参数&a…

机器学习基础16-建立预测模型项目模板

机器学习是一项经验技能&#xff0c;经验越多越好。在项目建立的过程中&#xff0c;实 践是掌握机器学习的最佳手段。在实践过程中&#xff0c;通过实际操作加深对分类和回归问题的每一个步骤的理解&#xff0c;达到学习机器学习的目的 预测模型项目模板 不能只通过阅读来掌握…

阿里云将关停代销业务

我是卢松松&#xff0c;点点上面的头像&#xff0c;欢迎关注我哦&#xff01; 阿里云自从逐渐分拆独立之后&#xff0c;做了很多调整。最近它又做了一个大动作&#xff1a;据DoNews消息&#xff0c;阿里云将会在今年9月30日之前&#xff0c;全面关停代销业务。 这件事实际上…

C#_多线程编程入门

字面理解&#xff1a;多个线程同时工作的过程。 案例① 单线程 #region ① 单线程做菜/// <summary>/// ① 单线程做菜:执行任务时,什么操作都动不了./// </summary>/// <param name"sender"></param>/// <param name"e">…

Linux通信--构建进程通信IPC的方案之共享内存|实现使用共享内存进行serverclient通信

共享内存是最快的IPC形式。一旦这样的内存映射到共享它的进程地址空间&#xff0c;这些进程间数据传递不再涉及到内核&#xff0c;即进程不再通过执行进入内核的系统调用来传递彼此的数据。 目录 一、共享内存的原理 二、使用共享内存 三、共享内存函数 1.shmget(用来创建共…

研华I/O板卡 Win10+Qt+Cmake 开发环境搭建

文章目录 一.研华I/O板卡 Win10QtCmake 开发环境搭建 一.研华I/O板卡 Win10QtCmake 开发环境搭建 参考这个链接安装研华I/O板卡驱动程序系统环境变量添加研华板卡dll Qt新建一个c项目 cmakeList.txt中添加研华库文件 cmake_minimum_required(VERSION 3.5)project(advantechDA…

基于爬行动物算法优化的BP神经网络(预测应用) - 附代码

基于爬行动物算法优化的BP神经网络&#xff08;预测应用&#xff09; - 附代码 文章目录 基于爬行动物算法优化的BP神经网络&#xff08;预测应用&#xff09; - 附代码1.数据介绍2.爬行动物优化BP神经网络2.1 BP神经网络参数设置2.2 爬行动物算法应用 4.测试结果&#xff1a;5…

【C++】—— C++11之可变参数模板

前言&#xff1a; 在C语言中&#xff0c;我们谈论了有关可变参数的相关知识。在C11中引入了一个新特性---即可变参数模板。本期&#xff0c;我们将要介绍的就是有关可变参数模板的相关知识&#xff01;&#xff01;&#xff01; 目录 序言 &#xff08;一&#xff09;可变参…