Zlrrr
作者:互联网
#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; }
标签:node,int,dep,maxn,lev,root,Zlrrr 来源: https://www.cnblogs.com/zlrrrr/p/10623778.html