当前位置:网站首页>先中二叉建树
先中二叉建树
2022-04-23 03:03:00 【学习kl&tk】
#include <bits/stdc++.h>
using namespace std;
struct TreeNode {
char val;
TreeNode* l;
TreeNode* r;
};
// TODO(递归到当前这一层, mid 为 当前构建这颗树中序节点 ,hou 当前的后序遍历节点)
// TODO len 当前构建这颗树的节点个数
int ans = 0;
TreeNode* build(char xian[], char mid[], int len, int high) {
if (len == 0) return NULL;
ans = max(ans, high);
char tmp = xian[0];
int index = -1;
for(int i = 0; i < len; i++) {
if (tmp == mid[i]) {
index = i ;
break;
}
}
TreeNode* root = new TreeNode();
root->val = tmp;
// todo 建左子树
// todo 1. xian + 1 ~ xian + index 先序范围
// todo 2. mid + 0 ~ mid + index - 1
root->l = build(xian + 1, mid, index, high + 1);
// todo 建右子树
// todo 1. xian + index + 1 ~ xian + index + 1 + (len - index - 1) - 1 线序中右子树的范围
// todo 2. mid + index + 1 ~
root->r = build(xian + index + 1, mid + index + 1, len - index - 1, high + 1);
return root;
}
char a[55], b[55];
int main() {
ios::sync_with_stdio(false);
int n;
cin >> n;
for(int i = 0; i < n; i++) cin >> a[i];
for(int i = 0; i < n; i++) cin >> b[i];
TreeNode* root = build(a, b, n, 1);
cout << ans << endl;
return 0;
}
版权声明
本文为[学习kl&tk]所创,转载请带上原文链接,感谢
https://blog.csdn.net/weixin_53013914/article/details/124325721
边栏推荐
猜你喜欢

最通俗易懂的依赖注入与控制反转
![[format] simple output (2)](/img/24/64739f5e6bbd54bfa9fb78b8c53c94.png)
[format] simple output (2)

Huawei machine test question -- deformation of hj53 Yang Hui triangle

Small companies don't make formal offers

Openfeign timeout setting

.NET点滴:说说Middleware构造中获取不到Scoped服务的问题

JS learning notes
![Niuke white moon race 6 [solution]](/img/c5/6c59378c3bb12efa60ab3a8cd2c943.png)
Niuke white moon race 6 [solution]

MYSQL03_ SQL overview, rules and specifications, basic select statements, display table structure

C# WPF UI框架MahApps切换主题
随机推荐
Chapter V project quality management of information system project manager summary
How to count the number of all files in a directory under win10 system
Kubernetes - Introduction to actual combat
Basic workflow of CPU
Laravel8- use JWT
Deep q-network (dqn)
C#中切片语法糖的使用
Kubernetes - detailed explanation of pod
L2-006 树的遍历(中后序确定二叉树&层序遍历)
ASP.NET 6 中间件系列 - 执行顺序
Source code interpretation of Flink index parameters (read quantity, sent quantity, sent bytes, received bytes, etc.)
Openfeign timeout setting
How to deploy a website with only a server and no domain name?
Winsock programming interface experiment: Ping
Laravel's own paging query
Thoughts on the 2022 national network security competition of the national secondary vocational group (only one idea for myself) - network security competition questions (10)
BLDC double closed loop (speed PI + current PI) Simulink simulation model
VirtualBox virtual machine (Oracle VM)
Liunx foundation - zabbix5 0 monitoring system installation and deployment
Systemctl start Prometheus + grafana environment