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

使用sqlcipher打开加密的sqlite方法

JSP webshell free -- webshell free

How to get the password of cpolar?

互联网快讯:腾讯会议应用市场正式上线;Soul赴港递交上市申请书

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

Hdu1234 door opener and door closer (water question)

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

axis设备的rtsp setup头中的url不能带参

LeetCode+ 76 - 80 暴搜专题

UVM learning - build a simple UVM verification platform
随机推荐
Overview of integrated learning
二叉树专题--【深基16.例7】普通二叉树(简化版)(multiset 求前驱 后继 哨兵法)
从MediaRecord录像中读取H264参数
How to get the password of cpolar?
记录 AttributeError: ‘NoneType‘ object has no attribute ‘nextcall‘
二叉树专题--P1030 [NOIP2001 普及组] 求先序排列
JS settimeout() and interview questions
PCL eigen introduction and simple use
4. Random variables
Shutter - canvas custom graph
MySQL lethal serial question 4 -- are you familiar with MySQL logs?
SPSS做Shapiro-Wilk正态分析
【AppLinking实战案例】通过AppLinking分享应用内图片
1287_ Implementation analysis of prvtaskistasksuspended() interface in FreeRTOS
UVM factory mechanism
面对不确定性,供应链的作用
C#中索引器
12. Process synchronization and semaphore
13. Semaphore critical zone protection
点云投影图片