这样建树会报错
#include<iostream>
#include<algorithm>
#include<queue>
#include<stdlib.h>
using namespace std;
const int maxn = 1000;
int n, l, r, num = 0;
int ori[maxn], in[maxn], lay[maxn] = { 0 };
struct Node {
int data;
Node* lchild;
Node* rchild;
}*node[maxn];
void inOrder(Node* root) {
if (root == NULL) return;
inOrder(root->lchild);
root->data = ori[num++];
inOrder(root->rchild);
}
void layer(Node* root) {
queue<Node*> q;
q.push(root);
while (!q.empty()) {
Node* front = q.front();
cout << front->data;
if (num < n) {
cout << " ";
num++;
}
q.pop();
if (front->lchild != NULL) q.push(front->lchild);
if (front->rchild != NULL) q.push(front->rchild);
}
}
int main() {
cin >> n;
for (int i = 0; i < n; i++) {
cin >> l >> r;
if (l == -1) {
node[i]->lchild = NULL;
}
else {
node[l] = new Node;
node[i]->lchild = new Node;
node[i]->lchild = node[l];
}
if (r == -1) {
node[i]->rchild = NULL;
}
else {
node[r] = new Node;
node[i]->rchild = node[r];
}
}
for (int i = 0; i < n; i++) {
cin >> ori[i];
}
sort(ori, ori + n);
inOrder(node[0]);
num = 0;
return 0;
}