PAT 7-4 Cartesian Tree (30分)
5555还是这门考试,这道30分的题这么简单我是没想到的,还是我下午思维活跃早上思维缓慢?(早上做第一题第二题第三题各花一小时导致没时间做第四题)
第四题的思路:
1.在序列中找出最小值为根
2.运用递归思想,因为中序遍历的缘故,序列中根左边的值属于根的左子树,右边同理。于是写递归函数,每次在序列中找最小值,即根,对根左边建子树,右边建子树
3.层序遍历输出
代码如下:
#include <iostream> #include <vector> #include <algorithm> #include <map> #include <queue> using namespace std; struct node{ int data; node* left; node* right; }; int a[31]; int n; node* dfs(int l,int r){ if(l>r)return nullptr; int minnum=9999999,ind; for(int i=l;i<=r;i++){ if(a[i]<minnum){ minnum=a[i]; ind=i; } } node* root=new node; root->data=minnum; root->left=dfs(l,ind-1); root->right=dfs(ind+1,r); return root; } void level_order(node* root){ queue<node*> q; q.push(root); int num=0; while (!q.empty()){ node* tmp=q.front(); q.pop(); printf("%d",tmp->data); num++; if(num<n)printf(" "); if(tmp->left!= nullptr)q.push(tmp->left); if(tmp->right!= nullptr)q.push(tmp->right); } } int main(){ cin>>n; for(int i=0;i<n;i++){ cin>>a[i]; } node* root; root=dfs(0,n-1); level_order(root); return 0; }

浙公网安备 33010602011771号