【PAT甲级】1123 Is It a Complete AVL Tree (30分)(AVL树建树,层次遍历)

题意:

输入一个正整数N(<=20),接着输入N个结点,建立一颗AVL树,输出层次遍历,并输出是否为完全二叉树。

trick:

给树创建根节点时用NULL不要用new。。。

AAAAAccepted code:

 1 #define HAVE_STRUCT_TIMESPEC
 2 #include<bits/stdc++.h>
 3 using namespace std;
 4 int a[27];
 5 typedef struct node{
 6     int val;
 7     node *left,*right;
 8     int data;
 9 };
10 node *left_rotate(node *root){
11     node *temp=root->right;
12     root->right=temp->left;
13     temp->left=root;
14     return temp;
15 }
16 node *right_rotate(node *root){
17     node *temp=root->left;
18     root->left=temp->right;
19     temp->right=root;
20     return temp;
21 }
22 node *left_right(node *root){
23     root->left=left_rotate(root->left);
24     return right_rotate(root);
25 }
26 node *right_left(node *root){
27     root->right=right_rotate(root->right);
28     return left_rotate(root);
29 }
30 int get_height(node *root){
31     if(root==NULL)
32         return 0;
33     return max(get_height(root->left),get_height(root->right))+1;
34 }
35 node *inser(node *root,int val){
36     if(root==NULL){
37         root=new node();
38         root->val=val;
39         root->left=root->right=NULL;
40     }
41     else if(val<root->val){
42         root->left=inser(root->left,val);
43         if(get_height(root->left)-get_height(root->right)>=2)
44             root=val<root->left->val?right_rotate(root):left_right(root);
45     }
46     else{
47         root->right=inser(root->right,val);
48         if(get_height(root->right)-get_height(root->left)>=2)
49             root=val>root->right->val?left_rotate(root):right_left(root);
50     }
51     return root;
52 }
53 int vis[47];
54 int main(){
55     ios::sync_with_stdio(false);
56     cin.tie(NULL);
57     cout.tie(NULL);
58     int n;
59     cin>>n;
60     for(int i=1;i<=n;++i)
61         cin>>a[i];
62     node *ans=NULL;
63     for(int i=1;i<=n;++i)
64         ans=inser(ans,a[i]);
65     queue<node *>q;
66     ans->data=1;
67     vis[1]=1;
68     q.push(ans);
69     cout<<ans->val;
70     while(!q.empty()){
71         node *now=new node();
72         now=q.front();
73         q.pop();
74         if(now->data!=1)
75             cout<<" "<<now->val;
76         if(now->left!=NULL){
77             vis[(now->data)*2]=1;
78             now->left->data=(now->data)*2;
79             q.push(now->left);
80         }
81         if(now->right!=NULL){
82             vis[(now->data)*2+1]=1;
83             now->right->data=(now->data)*2+1;
84             q.push(now->right);
85         }
86     }
87     int flag=0;
88     for(int i=1;i<=n;++i)
89         if(vis[i]==0)
90             flag=1;
91     if(flag)
92         cout<<"\nNO";
93     else
94         cout<<"\nYES";
95     return 0;
96 }

猜你喜欢

转载自www.cnblogs.com/ldudxy/p/12453773.html