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

代码随想录 Leetcode106. 从中序与后序遍历序列构造二叉树

题目:


代码(首刷看解析 2024年1月30日):

class Solution {
public:TreeNode* recursion(vector<int>& inorder, vector<int>& postorder, int longthOfLeft, int longthOfRight) {if (postorder.size() == 0) return nullptr;int splitPoint = postorder[postorder.size() - 1];TreeNode* root = new TreeNode(splitPoint);if (postorder.size() == 1) return root;int arrayLeft = 0;for (int i = 0; i < inorder.size(); ++i) {if (inorder[i] == splitPoint) {arrayLeft = i;break;}}int arrayRight = inorder.size() - arrayLeft - 1;vector<int> inorderLeft(inorder.begin(), inorder.begin() + arrayLeft);vector<int> inorderRight(inorder.begin() + arrayLeft + 1, inorder.end());postorder.resize(postorder.size() - 1);vector<int> postorderLeft(postorder.begin(), postorder.begin() + arrayLeft);vector<int> postorderRight(postorder.begin() + arrayLeft, postorder.end());root->left = recursion(inorderLeft,postorderLeft,arrayLeft,arrayRight);root->right = recursion(inorderRight,postorderRight,arrayLeft,arrayRight);return root;}TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {int splitPoint = postorder[postorder.size() - 1];int arrayLeft = 0;for (int i = 0; i < inorder.size(); ++i) {if (inorder[i] == splitPoint) {arrayLeft = i;break;}}int arrayRight = inorder.size() - arrayLeft - 1;return recursion(inorder,postorder,arrayLeft,arrayRight);}
};

思路

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

相关文章:

  • Log4j Log4j2
  • C语言——如何进行文件操作
  • python中for循环的几个现象
  • openssl3.2 - 测试程序的学习 - 准备openssl测试专用工程的模板
  • Delphi.cz采访​Embarcadero​捷克共和国办事处经理:理查德·库巴特 - 第一部分
  • AI投资或成科技裁员罪魁祸首
  • 解读BEVFormer,新一代自动驾驶视觉工作的基石
  • 【React教程】(1) React简介、React核心概念、React初始化
  • 云计算中的弹性是什么?
  • Vue3基础:pnpm是什么?npm和pnpm的区别?如何使用pnpm?
  • vue中父组件直接调用子组件方法(通过ref)
  • Gunicorn性能优化:提升Python Web应用的服务效率
  • 如何使用ssh key免密码登录服务器?
  • macos Android平台签名证书(.keystore)
  • Kotlin快速入门系列2
  • 单片机之keil软件环境搭建
  • 数学公式OCR识别php 对接mathpix api 使用公式编译器
  • MySQL原理(二)存储引擎(1)概述
  • 微信小程序canvas画布如何解决在for循环绘制图像显示不全的问题
  • Python计算机二级/Python期末考试 刷题(一)
  • 最新GPT4.0使用教程,AI绘画-Midjourney绘画,GPT语音对话使用,DALL-E3文生图+思维导图一站式解决
  • 【JavaScript】两种方法实现继承
  • 张维迎《博弈与社会》笔记(3)导论:一些经济学的基础知识
  • 随机生成UI不重叠
  • 【C/C++】C/C++编程——第一个 C++ 程序:HelloWorld
  • 扩散视觉反事实算法 DVC:对抗性鲁棒分类器 + 扩散模型,跨模态对比原始的 fundus 图 VS 生成的 OCT 图
  • C++(6) 继承
  • 【Servlet】Smart Tomcat插件简化Servlet开发流程及解决常见问题
  • 解决Qt连接不上mysql数据库
  • kubernetes-快速部署一套k8s集群