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博客

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

前闭后开就全都前闭后开

前开后闭就全都前开后闭

相关推荐
Gorgous—l27 分钟前
数据结构算法学习:LeetCode热题100-动态规划篇(下)(单词拆分、最长递增子序列、乘积最大子数组、分割等和子集、最长有效括号)
数据结构·学习·算法
hellokandy35 分钟前
C++ 如何知道程序最多可以申请多少内存
c++·vector·cin·cout
北京地铁1号线1 小时前
2.3 相似度算法详解:Cosine Similarity 与 Euclidean Distance
算法·余弦相似度
圣保罗的大教堂1 小时前
leetcode 1895. 最大的幻方 中等
leetcode
Remember_9931 小时前
【LeetCode精选算法】滑动窗口专题一
java·数据结构·算法·leetcode·哈希算法
凯子坚持 c2 小时前
Protocol Buffers C++ 进阶数据类型与应用逻辑深度解析
java·服务器·c++
窗边鸟2 小时前
小白日记之java方法(java复习)
java·学习
jiunian_cn2 小时前
【C++】IO流
开发语言·c++
小饼干超人2 小时前
详解向量数据库中的PQ算法(Product Quantization)
人工智能·算法·机器学习
你撅嘴真丑2 小时前
第四章 函数与递归
算法·uva