LeetCode Hot100 | Day6 | 从前序和中序数组构建二叉树

LeetCode Hot100 | Day6 | 从前序和中序数组构建二叉树

从前序和中序数组构建二叉树

105. 从前序与中序遍历序列构造二叉树 - 力扣(LeetCode)

c++ 复制代码
class Solution {
public:
    TreeNode *tra(vector<int> preorder, vector<int> inorder)
    {
        if(preorder.size()==0)
            return nullptr;
        int val=preorder[0];
        TreeNode* t=new TreeNode (val);
        int index=0;
        for(index=0;index<inorder.size();index++)
            if(val==inorder[index])
                break;
        t->left=tra(vector<int>(preorder.begin()+1,preorder.begin()+1+index),vector<int>(inorder.begin(),inorder.begin()+index));
        t->right=tra(vector<int>(preorder.begin()+1+index,preorder.end()),vector<int>(inorder.begin()+index+1,inorder.end()));
        return t;
    }
    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
        return tra(preorder,inorder);
    }
};

读者可以参考这篇博客来学习本题解法,思路都一样

代码随想录 | Day25 | 二叉树:从中序与后序遍历构造二叉树&&最大二叉树-CSDN博客

注意点:切割子树的前序和中序区间的时候要注意使用的区间要统一

前闭后开就全都前闭后开

前开后闭就全都前开后闭

相关推荐
沐风听雨_A1 小时前
雄迈IP摄像头配置笔记
笔记
wadesir1 小时前
Rust中的条件变量详解(使用Condvar的wait方法实现线程同步)
开发语言·算法·rust
yugi9878382 小时前
基于MATLAB实现协同过滤电影推荐系统
算法·matlab
TimberWill2 小时前
哈希-02-最长连续序列
算法·leetcode·排序算法
Morwit2 小时前
【力扣hot100】64. 最小路径和
c++·算法·leetcode
我命由我123452 小时前
SVG - SVG 引入(SVG 概述、SVG 基本使用、SVG 使用 CSS、SVG 使用 JavaScript、SVG 实例实操)
开发语言·前端·javascript·css·学习·ecmascript·学习方法
leoufung2 小时前
LeetCode 373. Find K Pairs with Smallest Sums:从暴力到堆优化的完整思路与踩坑
java·算法·leetcode
OliverH-yishuihan2 小时前
开发linux项目-在 Windows 上 基于“适用于 Linux 的 Windows 子系统(WSL)”
linux·c++·windows
七禾页丫2 小时前
面试记录12 中级c++开发工程师
c++·面试·职场和发展
wifi chicken3 小时前
数组遍历求值,行遍历和列遍历谁更快
c语言·数据结构·算法