代码随想录算法 - 二叉树3

news/2024/9/19 17:42:59/文章来源:https://www.cnblogs.com/code4log/p/18412691

题目1513. 找树左下角的值

给定一个二叉树的 根节点 root,请找出该二叉树的 最底层 最左边 节点的值。

假设二叉树中至少有一个节点。

示例 1:

img

输入: root = [2,1,3]
输出: 1

示例 2:

img

输入: [1,2,3,4,null,5,6,null,null,7]
输出: 7

提示:

  • 二叉树的节点个数的范围是 [1,104]
  • -231 <= Node.val <= 231 - 1

思路

迭代法

用辅助queue进行层序遍历就行了,直到最后一层遍历完,取出最左边的节点。

代码

class Solution {
public:int findBottomLeftValue(TreeNode* root) {if(!root->left && !root->right){return root->val;}queue<TreeNode*> nodeQueue;TreeNode* result;nodeQueue.push(root);while(!nodeQueue.empty()){int num = nodeQueue.size();if(num > 0){result = nodeQueue.front();}for(int i = 0; i < num; i++){TreeNode* curNode = nodeQueue.front();nodeQueue.pop();if(curNode->left){nodeQueue.push(curNode->left);}if(curNode->right){nodeQueue.push(curNode->right);}}}return result->val;}
};

递归法

用辅助变量maxdepth和depth来判断叶子节点是否是左下角的节点,其他的部分就先序遍历做就行了。

代码

class Solution {
public:int result;int maxDepth;void getResult(TreeNode* root, int depth){//碰到叶子节点判断是否为最深的左叶子if(!root->left && !root->right){if(depth > maxDepth){maxDepth = depth;result = root->val;}return;}if(root->left){getResult(root->left, depth + 1);}if(root->right)getResult(root->right, depth + 1);}int findBottomLeftValue(TreeNode* root) {maxDepth = INT_MIN;getResult(root, 0);return result;}
};

题目2 112. 路径总和

给你二叉树的根节点 root 和一个表示目标和的整数 targetSum 。判断该树中是否存在 根节点到叶子节点 的路径,这条路径上所有节点值相加等于目标和 targetSum 。如果存在,返回 true ;否则,返回 false

叶子节点 是指没有子节点的节点。

示例 1:

img

输入:root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22
输出:true
解释:等于目标和的根节点到叶节点路径如上图所示。

示例 2:

img

输入:root = [1,2,3], targetSum = 5
输出:false
解释:树中存在两条根节点到叶子节点的路径:
(1 --> 2): 和为 3
(1 --> 3): 和为 4
不存在 sum = 5 的根节点到叶子节点的路径。

示例 3:

输入:root = [], targetSum = 0
输出:false
解释:由于树是空的,所以不存在根节点到叶子节点的路径。

提示:

  • 树中节点的数目在范围 [0, 5000]
  • -1000 <= Node.val <= 1000
  • -1000 <= targetSum <= 1000

思路

递归法

用先序遍历,注意节点是否为叶子节点就行了。

代码

class Solution {
public:bool hasPathSum(TreeNode* root, int targetSum) {if(root == nullptr){return false;}int curVal = targetSum - root->val;if(curVal == 0 && !root->left && !root->right){return true;}return hasPathSum(root->left, curVal) || hasPathSum(root->right, curVal);     }
};

迭代法

我使用一个辅助栈stack<pair<TreeNode*, int>>对象来保存每个节点及剩余的路径,剩下的用什么遍历都可以找出目标叶子节点。

代码

class Solution {
public:bool hasPathSum(TreeNode* root, int targetSum) {if(root == nullptr){return false;}stack<pair<TreeNode*, int>> nodeStack;nodeStack.push(make_pair(root, targetSum));while(!nodeStack.empty()){auto iter = nodeStack.top();nodeStack.pop();if(!iter.first->left && !iter.first->right && iter.first->val == iter.second){return true;}if(iter.first->left){nodeStack.push(make_pair(iter.first->left, iter.second - iter.first->val));}if(iter.first->right){nodeStack.push(make_pair(iter.first->right, iter.second - iter.first->val));}}return false;}
};

题目3 106. 从中序与后序遍历序列构造二叉树

给定两个整数数组 inorderpostorder ,其中 inorder 是二叉树的中序遍历, postorder 是同一棵树的后序遍历,请你构造并返回这颗 二叉树

示例 1:

img

输入:inorder = [9,3,15,20,7], postorder = [9,15,7,20,3]
输出:[3,9,20,null,null,15,7]

示例 2:

输入:inorder = [-1], postorder = [-1]
输出:[-1]

迭代法

用的迭代法,思路和代码随想里的递归法类似。

代码

class Solution {
public:TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {if (inorder.empty() || postorder.empty()) return nullptr;// 根节点TreeNode* root = new TreeNode(postorder.back());postorder.pop_back(); // 删除最后一个元素,因为这是根节点// 找到根节点在 inorder 中的索引int rootIndex = 0;while (inorder[rootIndex] != root->val) {rootIndex++;}// 栈保存:parent节点,inorder左边界,inorder右边界,postorder左边界,postorder右边界,是否为左子树stack<tuple<TreeNode*, int, int, int, int, bool>> nodeStack;// 处理右子树if (rootIndex + 1 <= inorder.size() - 1) {nodeStack.push(make_tuple(root, rootIndex + 1, inorder.size() - 1, rootIndex, postorder.size() - 1, false));}// 处理左子树if (0 <= rootIndex - 1) {nodeStack.push(make_tuple(root, 0, rootIndex - 1, 0, rootIndex - 1, true));}// 遍历栈while (!nodeStack.empty()) {auto [parent, inStart, inEnd, postStart, postEnd, isLeft] = nodeStack.top();nodeStack.pop();// 新的根节点是后序遍历 postorder[postEnd] 的值TreeNode* curNode = new TreeNode(postorder[postEnd]);if (isLeft) {parent->left = curNode;} else {parent->right = curNode;}// 在 inorder 中找到当前节点的索引int inIndex = inStart;while (inorder[inIndex] != curNode->val) {inIndex++;}// 处理右子树if (inIndex + 1 <= inEnd) {nodeStack.push(make_tuple(curNode, inIndex + 1, inEnd, postEnd - (inEnd - inIndex), postEnd - 1, false));}// 处理左子树if (inStart <= inIndex - 1) {nodeStack.push(make_tuple(curNode, inStart, inIndex - 1, postStart, postStart + (inIndex - inStart) - 1, true));}}return root;}
};

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/796671.html

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

相关文章

Combinatorics/Probability/Expectation

前言 计数加训!!!! 以下问题都是数数。 一些纯组合问题 插板法 例 1 求 $\sum_{i=1}^kx_i=n$ 的解的组数,其中 $x_i\in \mathbb{N^+}$ 且 $x_i\ge a_i$。 考虑令 $x_i=x_i-a_i+1\ge 1$,于是有 $\sum_{i=1}^k x_i=n-k+\sum a_i$,于是答案为 $$n-k+\sum a_i-1\choose k-1$…

信息学奥赛初赛天天练-88-CSP-S2023阅读程序1-数据类型、unsigned 关键字、二进制、位运算、左移、右移、异或运算

信息学奥赛初赛天天练-88-CSP-S2023阅读程序1-数据类型、unsigned 关键字、二进制、位运算、左移、右移、异或运算 PDF文档公众号回复关键字:202409132023 CSP-S 阅读程序1 判断题正确填 √,错误填 ⨉ ;除特殊说明外,判断题 1.5 分,选择题 3 分,共计 40 分) 01 #include …

来云栖大会!探展云上开发,沉浸式体验云原生 + AI 新奇玩法

计算馆将展示中国最先进的云计算产业链全景,从底层硬件到数据创新,从云计算基础设施到数据管理服务、人工智能平台和模型服务,全景式呈现 AI 时代云计算最新技术形态和产品进展。2024 云栖大会来了! 本届云栖大会将于 9 月 19 日至 9 月 21 日 在杭州云栖小镇召开 汇集全球…

最后的记录

最后的挣扎但是做的题太少了根本算不上长征。 写这个是因为 NOIP2024 剩百日,这他妈是最后一次了,就让我拿个一等吧,别无所求了。 把之前做过的题都重新总结一遍,怎么说也都能吃透了。 P6880 JOI 2020 Final] オリンピックバス 给一个有向图,经过边有代价 \(C_i\),可以反…

ENSP 某台设备出现乱码的情况

故障现象:新建拓扑没问题,打开其他人发的拓扑就会出现乱码(或者打开ENSP的示例也会出现问题),配置文档正常可以正常导出不受影响。 故障发现时间:2022年底 故障原因:windows系统BUG,常见于inter 13代CPU(例如I5-13500) 处理方法1:重装系统(一劳永逸) 处理方法2:例…

10、Linux文本编辑器

文本编辑器 常见文本编辑器 WindowsNotepad(记事本) Sublime UltraEditLinuxVI/VIM nano Emacs Sed gedit KateVI 和 VIM 的区别VI全称:Visual Interface 创建时间:1976年 创建者:Bill JoyVIM全称:VI IMproved,即 VI 的升级版 创建时间:1991年 创建者:Bram Moolenaar …

vue2 + scss 全局引入 变量使用

百度以及时AI帮助说的配置方式都大差不差,但是我的总是报错,意思就是变量找不到,报错如下 For a guide and recipes on how to configure / customize this project,<br> 然后AI和文章写的vue.config.js的配置内容基本如下module.exports = {css: {loaderOptions: {scss:…

2024金砖大赛网络安全赛项区域选拔赛-简单的rce

1. Echo写入一句话木马蚁剑连接木马根目录下找到flag

Google Colab 简单使用

使用Google Colab需要谷歌账号和一点点魔法。注册好账号,找到我的云盘,可以点击右上角的log 跳转。我的云端银盘这里可以选择上传文件还是文件夹,还可以新建文件夹然后在这个文件夹中选择你要上传的文件。例如我这创建了一个train_test 的文件夹,然后上传了 test_ScVgIM0.z…

Go runtime 调度器精讲(四):运行 main goroutine

原创文章,欢迎转载,转载请注明出处,谢谢。0. 前言 皇天不负有心人,终于我们到了运行 main goroutine 环节了。让我们走起来,看看一个 goroutine 到底是怎么运行的。 1. 运行 goroutine 稍微回顾下前面的内容,第一讲 Go 程序初始化,介绍了 Go 程序是怎么进入到 runtime 的…

Python网页应用开发神器Dash 2.18.1稳定版本来啦

本文示例代码已上传至我的Github仓库:https://github.com/CNFeffery/dash-master Gitee同步仓库地址:https://gitee.com/cnfeffery/dash-master大家好我是费老师,上周Dash发布了2.18.0新版本,并于今天发布了可稳定使用的2.18.1版本(自古.1版本最稳✌),今天的文章中就将针…