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;

}

};

相关推荐
leisoo80977 小时前
财报数据怎么排雷本地化Python构建财务异常预警系统
人工智能·python·算法
qz_Serene8 小时前
C++:类和对象(上)
开发语言·c++
luj_17689 小时前
塔防牌:策略与卡牌的智慧碰撞
服务器·c语言·开发语言·经验分享·算法
wuyk5559 小时前
3.链表:用指针串联的动态数据结构
c语言·开发语言·数据结构·链表
郝学胜-神的一滴9 小时前
干货版《算法导论》17:二叉树核心原理、遍历逻辑与高阶实操全解
数据结构·c++·python·算法·计算机·编程
爱编程的小新☆10 小时前
【LeetCode】从递归到 Flood Fill:5 道题吃透 DFS 的选择、回溯与标记
java·算法·leetcode·深度优先·回溯·flood fill
Water_Sunzhipeng10 小时前
2024牛客暑期多校训练营1
算法
hetao173383710 小时前
2026-08-09~08-14 hetao1733837 的刷题记录
c++·算法
技术小黑10 小时前
RNN算法实战系列06 | LSTM 实现糖尿病探索与预测
rnn·算法·lstm
疯狂打码的少年10 小时前
【数据结构】二叉树的性质(五大性质+计算)
数据结构·笔记·算法