题目
堆是一棵完全二叉树,树中每个结点的值都不小于(或不大于)其左右孩子结点的值。
这是一道简单题。但是,本菜鸡对于堆的定义不了解。所以,卡住了。而且,这应该是本菜鸡第一次用指针的写法,完成的一道题目。
#includeusing namespace std; const int N=33; const int INF=0x3f3f3f3f; int num[N], res[N]; struct node{ int data; node* lchild; node* rchild; }; int n, idx=1; node* findMin(int l, int r){ int index, data=INF; if(l>r) return NULL; for(int i=l; i<=r; i++){ if(data>num[i]){ data=num[i]; index=i; } } node* root = new node; root->data=data; root->lchild=findMin(l, index-1); root->rchild=findMin(index+1, r); return root; } void BFS(node* root){ queue q; q.push(root); while(!q.empty()){ node* top = q.front(); q.pop(); res[idx++]=top->data; if(top->lchild!=NULL) q.push(top->lchild); if(top->rchild!=NULL) q.push(top->rchild); } } int main() { scanf("%d", &n); for(int i=1; i<=n; i++){ scanf("%d", &num[i]); } node* root = findMin(1, n); BFS(root); for(int i=1; i<=n; i++){ printf("%d", res[i]); if(i!=n) printf(" "); else printf("n"); } return 0; }



