LeetCode:889. 根据前序和后序遍历构造二叉树

class Solution {

public:

unordered_map<int,int>valToIndex;

TreeNode* constructFromPrePost(vector<int>& preorder, vector<int>& postorder) {

for(int i=0;i<postorder.size();i++){

valToIndex[postorder[i]]=i;

}

return build(preorder,0,preorder.size()-1,

postorder,0,postorder.size()-1);

}

TreeNode* build(vector<int>& preorder,int preStart,int preEnd,

vector<int>& postorder,int postStart,int postEnd){

if(preStart>preEnd){

return nullptr;

}

if(preStart==preEnd){

return new TreeNode(preorder[preStart]);

}

int rootVal=preorder[preStart];

int leftRootVal=preorder[preStart+1];

int index=valToIndex[leftRootVal];

int leftsize=index-postStart+1;

//先构造出当前根节点

TreeNode* root=new TreeNode(rootVal);

root->left=build(preorder,preStart+1,preStart+leftsize,

postorder,postStart,index);

root->right=build(preorder,preStart+leftsize+1,preEnd,

postorder,index+1,postEnd-1);

return root;

}

};

相关推荐
努力学算法的蒟蒻几秒前
day41(12.22)——leetcode面试经典150
算法·leetcode·面试
liliangcsdn1 分钟前
Python拒绝采样算法优化与微调模拟
人工智能·算法·机器学习
Christo33 分钟前
2024《A Rapid Review of Clustering Algorithms》
人工智能·算法·机器学习·数据挖掘
AndrewHZ6 分钟前
【图像处理基石】图像梯度:核心算法原理与经典应用场景全解析
图像处理·算法·计算机视觉·cv·算子·边缘提取·图像梯度
让学习成为一种生活方式6 分钟前
组蛋白短链酰化修饰--文献精读187
算法
ULTRA??8 分钟前
基于range的函数式编程C++,python比较
c++·python·kotlin·c++20
fei_sun11 分钟前
数字图像处理
人工智能·算法·计算机视觉
Tisfy14 分钟前
LeetCode 960.删列造序 III:动态规划(最长递增子序列)
算法·leetcode·动态规划·字符串·题解·逆向思维
多米Domi01116 分钟前
0x3f第十天复习(考研日2)(9.18-12.30,14.00-15.00)
python·算法·leetcode
listhi52020 分钟前
支持向量机多分类解决方案
算法·支持向量机·分类