当前位置:网站首页>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 free -- webshell free

Easyexcel, a concise, fast and memory saving excel processing tool

Internet News: Tencent conference application market was officially launched; Soul went to Hong Kong to submit the listing application

MySQL数据库远程访问权限设置

12.进程同步与信号量

Shell programming 01_ Shell foundation

MongoDB 学习整理(条件操作符,$type 操作符,limit()方法,skip() 方法 和 sort() 方法)

如何使用IDE自动签名调试鸿蒙应用

Open the encrypted SQLite method with sqlcipher

使用华为性能管理服务,按需配置采样率
随机推荐
12.进程同步与信号量
JVM之垃圾回收器
二叉树专题--洛谷 P1229 遍历问题(乘法原理 已知前、后序遍历求中序遍历个数)
UVM - configuration mechanism
UVM learning - object attribute of UVM phase
对话吴纲:我为什么笃信“大国品牌”的崛起?
Shutter - canvas custom graph
【付费推广】常见问题合集,推荐榜单FAQ
[SUCTF2018]followme
(5) Gear control setting of APA scene construction
In the face of uncertainty, the role of supply chain
【AGC】如何解决事件分析数据本地和AGC面板中显示不一致的问题?
Hdu1228 a + B (map mapping)
洛谷 P5536 【XR-3】核心城市(贪心 + 树形 dp 寻找树的中心)
记录 AttributeError: ‘NoneType‘ object has no attribute ‘nextcall‘
Is the account above changtou school safe?
学习open62541 --- [66] UA_String的生成方法
HDU1228 A + B(map映射)
Mysql database remote access permission settings
nodejs+express+mysql简单博客搭建