(好好复习是王道)
1115. Counting Nodes in a BST (30)
分析:简单题——将bst树构造出来,然后给每个节点打上高度。最后求出树的高度。然后count树高的节点数加上树高节点数-1就ok了
1 #include <iostream> 2 #include <cstdio> 3 4 #define MAXN 1003 5 using namespace std; 6 typedef struct Node{ 7 int key,hight; 8 int left,right; 9 }Node; 10 11 Node node[MAXN]; 12 int solve_hight[MAXN]; 13 int main() 14 { 15 int n,index1,index2,max,a,b; 16 scanf("%d",&n); 17 18 scanf("%d",&node[0].key); 19 node[0].left=node[0].right=-1; 20 for(int i=1;i<n;i++){ 21 scanf("%d",&node[i].key); 22 node[i].left=node[i].right=-1; 23 int j=0; 24 while(1){ 25 if(node[i].key>node[j].key) 26 if(node[j].right!=-1) 27 j=node[j].right; 28 else 29 { 30 node[j].right=i; 31 break; 32 } 33 else 34 if(node[j].left!=-1) 35 j=node[j].left; 36 else 37 { 38 node[j].left=i; 39 break; 40 } 41 } 42 } 43 index1=index2=0; 44 solve_hight[index2++]=0; 45 node[0].hight=1; 46 while(index1!=index2){ 47 if(node[index1].left!=-1){ 48 solve_hight[index2++]=node[index1].left; 49 node[node[index1].left].hight=node[index1].hight+1; 50 } 51 if(node[index1].right!=-1){ 52 solve_hight[index2++]=node[index1].right; 53 node[node[index1].right].hight=node[index1].hight+1; 54 } 55 index1++; 56 } 57 58 a=b=max=0; 59 for(int i=0;i<n;i++){ 60 if(node[i].left==-1&&node[i].right==-1&&node[i].hight>max)max=node[i].hight; 61 } 62 for(int i=0;i<n;i++){ 63 if(max==node[i].hight)a++; 64 if(max-1==node[i].hight)b++; 65 } 66 printf("%d + %d = %d\n",a,b,a+b); 67 68 return 0; 69 }
1099. Build A Binary Search Tree (30)
类似于上题的简单题,看来pat的题目是一年年变难,难度都被刷上去了。先构建树的框架,然后将所给序列中序遍历,最后层次遍历给出结果。每个人都要找到最适合自己,能最快写出的树的层次遍历的代码。
1 #include <iostream> 2 #include <cstdio> 3 #include <algorithm> 4 #define MAXN 105 5 using namespace std; 6 7 typedef struct Node{ 8 int left,right; 9 Node(){ 10 left=right=-1; 11 } 12 }Node; 13 Node node[MAXN]; 14 int keynum[MAXN],ans[MAXN],mid[MAXN],count_num; 15 void mid_travel(int index){ 16 if(node[index].left!=-1) 17 mid_travel(node[index].left); 18 19 mid[count_num++]=index; 20 if(node[index].right!=-1) 21 mid_travel(node[index].right); 22 23 } 24 int main() 25 { 26 int n,index1,index2; 27 scanf("%d",&n); 28 for(int i=0;i<n;i++) 29 scanf("%d%d",&node[i].left,&node[i].right); 30 index1=index2=0; 31 ans[index2++]=0; 32 33 while(index1!=index2){ 34 if(node[ans[index1]].left!=-1) 35 ans[index2++]=node[ans[index1]].left; 36 if(node[ans[index1]].right!=-1) 37 ans[index2++]=node[ans[index1]].right; 38 index1++; 39 } 40 for(int i=0;i<n;i++){ 41 scanf("%d",&keynum[i]); 42 } 43 //得到中序遍历序列 44 sort(keynum,keynum+n); 45 count_num=0; 46 mid_travel(0); 47 bool flag=false; 48 for(int i=0;i<n;i++){ 49 for(int j=0;j<n;j++) 50 if(ans[i]==mid[j]){ 51 if(!flag){ 52 printf("%d",keynum[j]); 53 flag=true; 54 }else 55 printf(" %d",keynum[j]); 56 break; 57 } 58 } 59 return 0; 60 }