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;

}

};

相关推荐
Want5952 分钟前
C/C++贪吃蛇小游戏
c语言·开发语言·c++
阿昭L1 小时前
堆结构与堆排序
数据结构·算法
2***57421 小时前
人工智能在智能投顾中的算法
人工智能·算法
草莓熊Lotso1 小时前
《算法闯关指南:动态规划算法--斐波拉契数列模型》--01.第N个泰波拉契数,02.三步问题
开发语言·c++·经验分享·笔记·其他·算法·动态规划
草莓熊Lotso2 小时前
Git 分支管理:从基础操作到协作流程(本地篇)
大数据·服务器·开发语言·c++·人工智能·git·sql
报错小能手2 小时前
C++异常处理 终极及总结
开发语言·c++
Algo-hx2 小时前
C++编程基础(九):预处理指令
c++
mit6.8247 小时前
bfs|栈
算法
CoderYanger9 小时前
优选算法-栈:67.基本计算器Ⅱ
java·开发语言·算法·leetcode·职场和发展·1024程序员节
jllllyuz9 小时前
Matlab实现基于Matrix Pencil算法实现声源信号角度和时间估计
开发语言·算法·matlab