当前位置:网站首页>二叉树专题--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;
}
};
边栏推荐
猜你喜欢

JSP webshell免杀——JSP的基础

Hdu1228 a + B (map mapping)

(五)APA场景搭建之挡位控制设置

13. Semaphore critical zone protection

二叉树专题--AcWing 3384. 二叉树遍历(已知先序遍历 边建树 边输出中序遍历)

The nanny level tutorial of flutter environment configuration makes the doctor green to the end

洛谷 P5536 【XR-3】核心城市(贪心 + 树形 dp 寻找树的中心)

MYSQL环境配置
![二叉树专题--洛谷 P3884 [JLOI2009]二叉树问题(dfs求二叉树深度 bfs求二叉树宽度 dijkstra求最短路)](/img/c2/bb85b681af0f78b380b1d179c7ea49.png)
二叉树专题--洛谷 P3884 [JLOI2009]二叉树问题(dfs求二叉树深度 bfs求二叉树宽度 dijkstra求最短路)

nodejs+express+mysql简单博客搭建
随机推荐
In the face of uncertainty, the role of supply chain
【付费推广】常见问题合集,推荐榜单FAQ
Dialogue Wu Gang: why do I believe in the rise of "big country brands"?
2.hacking-lab脚本关[详细writeup]
PCL Eigen介绍及简单使用
从MediaRecord录像中读取H264参数
Operator-1初识Operator
The nanny level tutorial of flutter environment configuration makes the doctor green to the end
Leetcode+ 76 - 80 storm search topic
Beautiful and intelligent, Haval H6 supreme+ makes Yuanxiao travel safer
首份中国企业敏捷实践白皮书发布| 附完整下载
对话吴纲:我为什么笃信“大国品牌”的崛起?
力扣(LeetCode)182. 查找重复的电子邮箱(2022.07.01)
SUS系统可用性量表
"Talking about podcasts" vol.352 the age of children: breaking the inner scroll, what can we do before high school?
全网显示 IP 归属地,是怎么实现的?
How to get the password of cpolar?
使用sqlcipher打开加密的sqlite方法
Record attributeerror: 'nonetype' object has no attribute 'nextcall‘
Read H264 parameters from mediarecord recording