提交时间:2024-01-23 17:26:47
运行 ID: 125608
//JC maoyu #include<bits/stdc++.h> using namespace std; const int maxn = 100000; int n; //使用结构体存储 struct tree { int left,right,data; }tree[maxn]; //建树 void build(int *node,int len){ for(int i=1;i<=len;i++){ tree[i].data = node[i]; int pos = 0,dir = 0; while(dir == 0){ if(node[i] < tree[pos].data){ if(tree[pos].left != -1) pos = tree[pos].left; else dir = 1; } else{ if(tree[pos].right != -1) pos = tree[pos].right; else dir = -1; } } dir == 1 ? tree[pos].left = i : tree[pos].right = i; } } //前序遍历输出 void pre(int root){ if(root != -1){ cout<<tree[root].data<<" "; pre(tree[root].left); pre(tree[root].right); } } int main() { int node[maxn]; cin>>n; for(int i=1;i<=n;i++) cin>>node[i]; for(int i=1;i<=maxn;i++){ tree[i].left = -1; tree[i].data = 0; tree[i].right = -1; } build(node,n); pre(1); return 0; } /* 9 6 3 8 5 2 9 4 7 10 */