constint M = 1e6 + 7; int front[M], mid[M], point = 0; //先序遍历,中序遍历,point指向当前要找的位置 int n; //有n个节点 int tree[M]; voidbuild(int idx, int l, int r){ if (point == n || l > r || l < 0 || r >= n) { //越界停止 return; } tree[idx] = front[point++]; int now = l; while (tree[idx] != mid[now] && now <= r) { now++; } build(idx * 2, l, now - 1); build(idx * 2 + 1, now + 1, r); }
int front[M], mid[M], point = -1; //先序遍历,中序遍历,point指向当前要找的位置 int n; //有n个节点 structTree { int l = -1, r = -1; } tree[M]; intbuild(int l, int r){ if (point == n - 1 || l > r || l < 0 || r >= n) { //越界停止 return0; } point++; int now = l; while (front[point] != mid[now] && now <= r) { now++; } tree[mid[now]] = {build(l, now - 1), build(now + 1, r)}; return mid[now]; }
constint M = 1e6 + 7; int front[M], mid[M], point = -1; //先序遍历,中序遍历,point指向当前要找的位置 int n; //有n个节点 structTree { int val; Tree *l, *r; Tree(int val) { this->val = val; l = NULL; r = NULL; } //构造函数,每次new一个新节点的时候对新节点进行初始化. }; Tree* build(int l, int r){ if (point == n - 1 || l > r || l < 0 || r >= n) { //越界停止 returnNULL; } point++; int now = l; while (front[point] != mid[now] && now <= r) { now++; } Tree* root = newTree(front[point]); root->l = build(l, now + 1); root->r = build(now + 1, r); return root; }