题目:1123 Is It a Complete AVL Tree
该题目综合了:1066 Root of AVL Tree与1110 Complete Binary Tree。
大致题意:给出一个包含N个元素的序列,构建一个平衡二叉树,然后判断其是否是一棵完全二叉树。
思路分析:先用七步口决构建平衡二叉树,然后按层序遍历,把二叉树的所有结点(包含空结点)入队,当第一次碰到队头是空结点时,如果队列中剩下的所有结点都是空结点,那么二叉树是完全二叉树,否则不是完全二叉树。
1 #include<iostream> 2 #include<queue> 3 #include<vector> 4 #include<algorithm> 5 using namespace std; 6 //第一步,定义AVL树 7 struct Node { 8 int v,height; 9 Node* lchild; 10 Node* rchild; 11 }; 12 //第二步,求以root为根结点的子树的高度 13 int getheight(Node* root) { 14 if(root == NULL) return 0; 15 return root->height; 16 } 17 //第三步,更新root的height 18 void updateheight(Node* root) { 19 root->height = max(getheight(root->lchild),getheight(root->rchild))+1; 20 } 21 //第四步,求root的平衡因子 22 int getbalancefactor(Node* root) { 23 return getheight(root->lchild)-getheight(root->rchild); 24 } 25 //第五步,左旋,记得更新树高 26 void L(Node* &root) { 27 Node* temp = root->rchild; 28 root->rchild = temp->lchild;//1 29 temp->lchild = root;//2 30 updateheight(root); 31 updateheight(temp); 32 root = temp;//3 33 } 34 //第六步,右旋 35 void R(Node* &root) { 36 Node* temp = root->lchild; 37 root->lchild = temp->rchild; 38 temp->rchild = root; 39 updateheight(root); 40 updateheight(temp); 41 root = temp; 42 } 43 //第七步,建立AVL树 44 void insert(Node* &root,int v) { 45 if(root == NULL) { 46 root = new Node; 47 root->v = v; 48 root->height = 1; 49 root->lchild = root->rchild = NULL; 50 return ; 51 } 52 if(v < root->v) { 53 insert(root->lchild,v);//向左子树插入 54 updateheight(root);//插入后更新树高 55 if(getbalancefactor(root) == 2) { 56 if(getbalancefactor(root->lchild) == 1)//LL型 57 R(root); 58 else if(getbalancefactor(root->lchild) == -1) { //LR型 59 L(root->lchild); 60 R(root); 61 } 62 } 63 } else { 64 insert(root->rchild,v);//向左子树插入 65 updateheight(root);//插入后更新树高 66 if(getbalancefactor(root) == -2) { 67 if(getbalancefactor(root->rchild) == -1)//RR型 68 L(root); 69 else if(getbalancefactor(root->rchild) == 1) { //RL型 70 R(root->rchild); 71 L(root); 72 } 73 } 74 } 75 } 76 77 vector<int> in; 78 bool BFS(Node* root) { 79 bool flag = true; 80 if(root == NULL) return flag;//空树 81 queue<Node*> q; 82 q.push(root); 83 while(!q.empty()) { 84 Node* node = q.front(); 85 q.pop(); 86 if(node != NULL) { 87 in.push_back(node->v); 88 q.push(node->lchild); 89 q.push(node->rchild); 90 } else { 91 while(!q.empty()) { 92 node = q.front(); 93 q.pop(); 94 if(node != NULL) { 95 in.push_back(node->v); 96 q.push(node->lchild);//别忘了入队非空结点的孩子结点 97 q.push(node->rchild); 98 flag = false; 99 } 100 } 101 } 102 } 103 return flag; 104 } 105 106 int main() { 107 int n,v; 108 cin>>n; 109 Node* root = NULL; 110 while(n--) { 111 cin>>v; 112 insert(root,v); 113 } 114 bool flag = BFS(root); 115 for(int i = 0; i < in.size(); ++i) { 116 if(i > 0) printf(" "); 117 printf("%d",in[i]); 118 } 119 if(flag) printf("\nYES"); 120 else printf("\nNO"); 121 return 0; 122 }