当前位置:网站首页>二叉树专题--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;
}
};
边栏推荐
- Beautiful and intelligent, Haval H6 supreme+ makes Yuanxiao travel safer
- 618 what is the secret of dominating the list again? Nike's latest financial report gives the answer
- Analysis of hot spots in AI technology industry
- 14. Code implementation of semaphore
- [visual studio] visual studio 2019 community version cmake development environment installation (download | install relevant components | create compilation execution project | error handling)
- Shell programming 01_ Shell foundation
- Use of vscode tool
- UVM learning - build a simple UVM verification platform
- 面对不确定性,供应链的作用
- 一招快速实现自定义快应用titlebar
猜你喜欢
随机推荐
js数组常用方法
13.信号量临界区保护
快应用中实现自定义抽屉组件
HDU1228 A + B(map映射)
长投学堂上面的账户安全吗?
[visual studio] visual studio 2019 community version cmake development environment installation (download | install relevant components | create compilation execution project | error handling)
二叉树专题--洛谷 P1229 遍历问题(乘法原理 已知前、后序遍历求中序遍历个数)
nodejs+express+mysql简单博客搭建
Set the playback speed during the playback of UOB equipment
Win11 arm系统配置.net core环境变量
Analysis of hot spots in AI technology industry
4. Random variables
拆解美图SaaS:开着飞机换引擎
SUS系统可用性量表
13. Semaphore critical zone protection
Mongodb quickly get started with some simple operations of mongodb command line
Common methods of JS array
1287_ Implementation analysis of prvtaskistasksuspended() interface in FreeRTOS
2022-06-17
简洁、快速、节约内存的Excel处理工具EasyExcel









