数组建 BST
#include <bits/stdc++.h> using namespace std; const int maxn = 1e5 + 10; int N, root = 1; int vis[maxn], dep[maxn]; vector<int> pre; vector<int> lev[maxn]; int depth = -1; struct Node{ int val; int l; int r; }node[maxn]; void order(int root) { if(!root) return; if(node[root].l != -1) order(node[root].l); if(node[root].r != -1) order(node[root].r); pre.push_back(node[root].val); } void levelorder(int root) { if(!root) return; queue<int> q; q.push(root); dep[root] = 1; while(!q.empty()) { int t = q.front(); q.pop(); lev[dep[t]].push_back(node[t].val); if(node[t].l != -1) q.push(node[t].l), dep[node[t].l] = dep[t] + 1, depth = max(depth, dep[node[t].l]); if(node[t].r != -1) q.push(node[t].r), dep[node[t].r] = dep[t] + 1, depth = max(depth, dep[node[t].r]); } } int main() { scanf("%d", &N); memset(vis, 0, sizeof(vis)); memset(dep, 0, sizeof(dep)); for(int i = 1; i <= N; i ++) { scanf("%d%d%d", &node[i].val, &node[i].l, &node[i].r); if(node[i].l != -1) vis[node[i].l] = 1; if(node[i].r != -1) vis[node[i].r] = 1; } while(vis[root]) root ++; levelorder(root); //printf("%d\n", depth); for(int i = 1; i <= depth; i ++) { if(i % 2 == 0) { for(int j = lev[i].size() - 1; j >= 0; j --) printf("%d ", lev[i][j]); } else { for(int j = 0; j < lev[i].size(); j ++) printf("%d ", lev[i][j]); } //printf("%d\n", lev[i].size()); } //for(int i = 0; i < lev.size(); i ++) //printf("%d%s", lev[i], i != lev.size() - 1 ? " " : "\n"); return 0; }
----------------------------------------------------
#include <bits/stdc++.h> using namespace std; int N, root = 0; int a[110]; struct Node{ int val; int l = -1; int r = -1; int fa = -1; int lev = 0; }node[110]; void BuildBST(int root, int x) { if(node[root].val > node[x].val) { if(node[root].l == -1) { node[root].l = x; node[x].fa = root; node[x].lev = node[root].lev + 1; } else BuildBST(node[root].l, x); } else if(node[root].val <= node[x].val) { if(node[root].r == -1) { node[root].r = x; node[x].fa = root; node[x].lev = node[root].lev + 1; } else BuildBST(node[root].r, x); } } int main() { scanf("%d", &N); for(int i = 0; i < N; i ++) { int x; scanf("%d", &x); node[i].val = x; } for(int i = 1; i < N; i ++) BuildBST(root, i); for(int i = 0; i < N; i ++) printf("%d %d %d %d %d\n", node[i].val, node[i].l, node[i].r, node[i].fa, node[i].lev); return 0; }