c++里结构体指针的使用
#include<bits/stdc++.h>
using namespace std;
const int N = 25;
// 定义二叉树节点结构体
struct node {
int val;
node* l, *r; // 改为指针类型
};
node v[N];
int mid[25];
int pos[25];
int you[25];
int zuo[25];
// 根据中序和后序遍历构建二叉树
node* build(int l, int r, int x, int y) {
if (x > y) return nullptr; // 使用 nullptr 表示空指针
int ta = pos[y];
node* head = new node; // 创建新节点
head->val = ta; // 赋值
if (x == y) return head;
int t = 0;
for (int i = 1; i <= r - l + 1; i++) {
if (mid[l + i - 1] == ta) {
t = i + l - 1;
break;
}
}
head->l = build(l, t - 1, x, x + t - l - 1);
head->r = build(t + 1, r, x + t - l, y - 1);
return head;
}
int main() {
int n;
cin >> n; // 读取节点数量
for (int i = 1; i <= n; i++) {
cin >> mid[i];
}
for (int i = 1; i <= n; i++) {
cin >> pos[i];
}
node* rt = build(1, n, 1, n);
node* q[30];
int hh = 0, tt = -1;
q[++tt] = rt;
int zz = 0, yy = 0;
while (hh <= tt) {
int sz = tt - hh + 1;
for (int i = 0; i < sz; i++) {
node* cur = q[hh++];
if (i == 0) zuo[zz++] = cur->val;
if (i == sz - 1) you[yy++] = cur->val;
if (cur->l != nullptr) {
q[++tt] = cur->l;
}
if (cur->r != nullptr) {
q[++tt] = cur->r;
}
}
}
cout<<"R:"; for (int i = 0; i < yy; i++) {
cout << " " << you[i];
} cout << endl;
cout<<"L:";
for (int i = 0; i < zz; i++) {
cout << " " << zuo[i];
}
return 0;
}