1. 程式人生 > 實用技巧 >PAT Heap Paths (30分)

PAT Heap Paths (30分)

這道題的思路分為三步;

一 根據給出的層序遍歷序列建樹。

題目中寫明是完全二叉樹,那麼就按照層序遍歷的程式碼,對一些內容進行修改,即可建樹,建完後建議寫個遍歷函式檢驗一下是否建立對了。

二 寫dfs函式從根到葉輸出路徑

根據輸出要求,這種需要設定一個向量vector path,在dfs的過程中向path中新增值,判斷到達葉結點時輸出路徑。

三 判斷是最小堆還是最大堆

這裡需要設定兩個flag,flag1和flag2。有很多方法判斷,我圖省事,採用的是將向量使用stl庫函式sort兩遍,一次升序一次降序,觀察哪次和原向量相等,然後依據結果設定flag。

具體程式碼如下:

#include <iostream>
#include 
<queue> #include <algorithm> using namespace std; struct node{ int data; node* left; node* right; }; int n; int a[1000]; node* level_order(){ queue<node*>q; node* root=new node; root->data=a[0]; root->left= nullptr; root->right= nullptr; q.push(root);
int ind=0; while (!q.empty()){ node* tmp=q.front(); q.pop(); ind++; if(ind<n){ node* l=new node; l->data=a[ind]; l->left= nullptr; l->right= nullptr; tmp->left=l; q.push(l); } ind
++; if(ind<n){ node* r=new node; r->data=a[ind]; r->left= nullptr; r->right= nullptr; tmp->right=r; q.push(r); } } return root; } vector<int> path; int flag1=0; int flag2=0; void dfs(node* root){ if(root== nullptr)return; if(root->left==nullptr&&root->right== nullptr) { if(path.empty())return; else{ path.push_back(root->data); for(int i=0;i<path.size();i++){ cout<<path[i]; if(i<path.size()-1)cout<<" "; } vector<int> tmp1=path,tmp2=path; sort(tmp1.begin(),tmp1.end()); sort(tmp2.begin(),tmp2.end(),greater<int>()); if(tmp1==path){ flag1=1; } else if(tmp2==path){ flag2=1; } else{ flag2=0; flag1=0; } path.pop_back(); cout<<endl; return; } } path.push_back(root->data); dfs(root->right); dfs(root->left); path.pop_back(); } int main(){ cin>>n; for(int i=0;i<n;i++){ cin>>a[i]; } node* root=level_order(); dfs(root); if(flag1==1&&flag2==0)cout<<"Min Heap"; else if(flag1==0&&flag2==1)cout<<"Max Heap"; else cout<<"Not Heap"; return 0; }