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;

}

};

相关推荐
北顾笙9801 分钟前
day38-数据结构力扣
数据结构·算法·leetcode
m0_629494733 分钟前
LeetCode 热题 100-----14.合并区间
数据结构·算法·leetcode
xin_nai7 分钟前
LeetCode热题100(Java)(5)普通数组
算法·leetcode·职场和发展
旖-旎17 分钟前
深搜练习(组合)(5)
c++·算法·深度优先·力扣
vegetablesssss18 分钟前
vtk镜像图
c++·qt·vtk
@小码农34 分钟前
2026年3月Scratch图形化编程等级考试一级真题试卷
开发语言·数据结构·c++·算法
【 】4231 小时前
C++&STL(Standard Template Library,标准模板库)
java·开发语言·c++
Wect1 小时前
LeetCode 5. 最长回文子串:DP + 中心扩展
前端·算法·typescript
一只牛_0071 小时前
pthread亲和性继承的一个坑:main绑核让整个进程退化到单核
c++
糖果店的幽灵1 小时前
决策树详解与sklearn实战
算法·决策树·sklearn