当前位置:网站首页>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;
}
};
边栏推荐
- JSP webshell免杀——webshell免杀
- PCL eigen introduction and simple use
- In the face of uncertainty, the role of supply chain
- Database dictionary Navicat automatic generation version
- Hdu1228 a + B (map mapping)
- 二叉树专题--【深基16.例7】普通二叉树(简化版)(multiset 求前驱 后继 哨兵法)
- UVM——Callback
- 二叉树专题--AcWing 1589. 构建二叉搜索树
- Shutter - canvas custom graph
- 【TS】1368- 秒懂 TypeScript 泛型工具类型!
猜你喜欢
![[TS] 1368 seconds understand typescript generic tool types!](/img/2b/58a850b52ce8a9b2e6e7b6b72b0fe5.jpg)
[TS] 1368 seconds understand typescript generic tool types!

软件产品管理系统有哪些?12个最佳产品管理工具盘点

Hdu1234 door opener and door closer (water question)

【AppLinking实战案例】通过AppLinking分享应用内图片

使用华为性能管理服务,按需配置采样率

Shutter - canvas custom graph

【AGC】如何解决事件分析数据本地和AGC面板中显示不一致的问题?

Shapiro Wilk normal analysis by SPSS

最详细MySql安装教程

华为快应用中如何实现同时传递事件对象和自定义参数
随机推荐
点云投影图片
PCL 从一个点云中提取一个子集
UVM——Callback
PCL之滤波
面对不确定性,供应链的作用
UVM factory mechanism
HDU1234 开门人和关门人(水题)
实验电镜距离测量之Matlab处理
Is the account above changtou school safe?
nodejs+express+mysql简单博客搭建
Use WinDbg to statically analyze dump files (summary of practical experience)
1287_FreeRTOS中prvTaskIsTaskSuspended()接口实现分析
JSP webshell免殺——JSP的基礎
"Matching" is true love, a new attitude for young people to make friends
UVM - configuration mechanism
Sus system availability scale
Set the playback speed during the playback of UOB equipment
二叉树专题--洛谷 P1229 遍历问题(乘法原理 已知前、后序遍历求中序遍历个数)
JSP webshell免杀——webshell免杀
Pywin32 opens the specified window