当前位置:网站首页>Special topic of binary tree -- acwing 18 Rebuild the binary tree (construct the binary tree by traversing the front and middle order)
Special topic of binary tree -- acwing 18 Rebuild the binary tree (construct the binary tree by traversing the front and middle order)
2022-07-02 10:58:00 【Morgannr】

The idea and code are similar to the previous question AcWing 1497. Tree traversal , I won't go into too much detail here .
Code :
class Solution {
public:
#define map unordered_map
map<int, int> d;
vector<int> pre, in;
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
pre = preorder, in = inorder;
int n = inorder.size();
for (int i = 0; i < n; ++i)
{
d[in[i]] = i;
}
return dfs(0, n - 1, 0, n - 1);
}
TreeNode* dfs(int pl, int pr, int il, int ir)
{
if (pl > pr) return nullptr;
auto root = new TreeNode(pre[pl]);
int k = d[root->val];
TreeNode* le, * ri;
le = dfs(pl + 1, k - il + pl, il, k - 1);
ri = dfs(k - il + pl + 1, pr, k + 1, ir);
root->left = le, root->right = ri;
return root;
}
};
边栏推荐
- MySQL environment configuration
- PCL extracts a subset from a point cloud
- What are the popular frameworks for swoole in 2022?
- Introduction to MySQL 8 DBA foundation tutorial
- SPSS做Shapiro-Wilk正态分析
- QT学习日记8——资源文件添加
- Shapiro Wilk normal analysis by SPSS
- 转换YV12到RGB565图像转换,附YUV转RGB测试
- 洛谷 P1892 [BOI2003]团伙(并查集变种 反集)
- Database dictionary Navicat automatic generation version
猜你喜欢

LeetCode+ 76 - 80 暴搜专题

shell编程01_Shell基础

Mongodb quickly get started with some simple operations of mongodb command line

Hdu1228 a + B (map mapping)

QT学习日记8——资源文件添加

Easyexcel, a concise, fast and memory saving excel processing tool

【AI应用】海康威视iVMS-4200软件安装

二叉树专题--AcWing 18. 重建二叉树(利用前、中序遍历,构建二叉树)

从.bag文件中读取并保存.jpg图片和.pcd点云

Sus system availability scale
随机推荐
[SUCTF2018]followme
Session cookies and tokens
Is the account above changtou school safe?
UVM - usage of common TLM port
洛谷 P3398 仓鼠找 sugar(树上倍增 lca 判断树中两条路径是否相交 结论)
【ARK UI】HarmonyOS ETS的启动页的实现
Mysql database remote access permission settings
软件产品管理系统有哪些?12个最佳产品管理工具盘点
JSP webshell免杀——webshell免杀
快应用中实现自定义抽屉组件
Thanos Receiver
Is this code PHP MySQL redundant?
LabVIEW为什么浮点数会丢失精度
如何使用IDE自动签名调试鸿蒙应用
Hdu1236 ranking (structure Sorting)
拆解美图SaaS:开着飞机换引擎
JSP webshell free -- webshell free
UVM——Callback
二叉树专题--AcWing 18. 重建二叉树(利用前、中序遍历,构建二叉树)
12.进程同步与信号量