当前位置:网站首页>二叉树专题--AcWing 18. 重建二叉树(利用前、中序遍历,构建二叉树)
二叉树专题--AcWing 18. 重建二叉树(利用前、中序遍历,构建二叉树)
2022-07-02 07:21:00 【Morgannr】
思路和代码均类似与上一题 AcWing 1497. 树的遍历,此处就不做过多赘述了。
代码:
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;
}
};
边栏推荐
- 点云投影图片
- axis设备的rtsp setup头中的url不能带参
- Hdu1236 ranking (structure Sorting)
- MySQL lethal serial question 4 -- are you familiar with MySQL logs?
- MySQL lethal serial question 3 -- are you familiar with MySQL locks?
- The nanny level tutorial of flutter environment configuration makes the doctor green to the end
- [visual studio] visual studio 2019 community version cmake development environment installation (download | install relevant components | create compilation execution project | error handling)
- 二叉树专题--【深基16.例7】普通二叉树(简化版)(multiset 求前驱 后继 哨兵法)
- Session cookies and tokens
- Use WinDbg to statically analyze dump files (summary of practical experience)
猜你喜欢
二叉树专题--洛谷 P1229 遍历问题(乘法原理 已知前、后序遍历求中序遍历个数)
Shell programming 01_ Shell foundation
华为应用市场应用统计数据问题大揭秘
nodejs+express+mysql简单博客搭建
JSP webshell免杀——JSP的基础
Dialogue Wu Gang: why do I believe in the rise of "big country brands"?
Operator-1 first acquaintance with operator
How to get the password of cpolar?
Disassembling Meitu SaaS: driving the plane to change the engine
Thanos Receiver
随机推荐
HDU1236 排名(结构体排序)
js promise.all
From Read and save in bag file Jpg pictures and PCD point cloud
集成学习概览
14. Code implementation of semaphore
Convert yv12 to rgb565 image conversion, with YUV to RGB test
Hdu1234 door opener and door closer (water question)
【AGC】构建服务3-认证服务示例
Windows环境MySQL8忘记密码文件解决方案
大华设备播放过程中设置播放速度
Win11 arm系统配置.net core环境变量
618 what is the secret of dominating the list again? Nike's latest financial report gives the answer
PCL Eigen介绍及简单使用
学习open62541 --- [66] UA_String的生成方法
UWA report uses tips. Did you get it? (the fourth bullet)
二叉树专题--洛谷 P1229 遍历问题(乘法原理 已知前、后序遍历求中序遍历个数)
MYSQL环境配置
华为快应用中如何实现同时传递事件对象和自定义参数
PCL 点云转深度图像
数据库字典Navicat自动生成版本