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++){

valToIndexpostorder\[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(preorderpreStart);

}

int rootVal=preorderpreStart;

int leftRootVal=preorderpreStart+1;

int index=valToIndexleftRootVal;

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;

}

};

相关推荐
地平线开发者8 小时前
J6B vio scenario sample
算法
BothSavage20 小时前
Trae远程开发中DeepSeek自定义模型4054错误的排查与修复
算法
小林ixn20 小时前
从暴力到KMP:一道题彻底搞懂字符串匹配的前世今生
算法
烬羽1 天前
字符串算法入门:从反转字符串到回文判断,面试不再慌
算法·面试
郝学胜_神的一滴1 天前
CMake 034:生成器表达式:解耦构建时序、精简分支逻辑的终极利器
c++·cmake
先吃饱再说2 天前
判断回文字符串,从一行代码到双指针优化
算法
见过夏天2 天前
C++ 基础入门完全指南
c++
黄敬峰2 天前
深入理解算法核心:从递归思想、数组扁平化到快速排序
算法