目录
1,题目描述
Sample Input 1:
5
88 70 61 63 65
Sample Output 1:
70 63 88 61 65
YES
Sample Input 2:
8
88 70 61 96 120 90 65 68
Sample Output 2:
88 65 96 61 70 90 120 68
NO
题目大意
根据给定序列构建AVL树,并输出AVL树的层次遍历,并判断是否为完全二叉树。
2,思路
(这一题是把以前的两道题合在一起了。。。)
@&再见萤火虫&【PAT_甲级_1066 Root of AVL Tree (25point(s)) (C++)【AVL树构建过程图解】】
@&再见萤火虫&【PAT_甲级_1110 Complete Binary Tree (25point(s)) (C++)【完全二叉树】】
算法
1,构建AVL树:
LL/RR/LR/RL型旋转:
计算树的高度
向AVL树中插入节点
2,利用队列层次遍历AVL树 :
3,利用DFS计算节点的最远距离maxDep(即将树放在下标从1开始的数组中,下标可达的最远位置,也就是最后一个节点的位置,若maxDep大于N,说明数组中间有部分节点未填充)判断是否为完全二叉树;
3,AC代码
#include<bits/stdc++.h>
using namespace std;
int N, maxDep = 0; //maxDep判断是否为完全二叉树
vector<int> level;
struct node{
int key;
node *left = NULL, *right = NULL;
};
int getHeight(node *tree){
if(tree == NULL)
return 0;
return max(getHeight(tree->left), getHeight(tree->right)) + 1;
}
node *LL(node *root){ //不需要node *root
node *tem = root->left;
root->left = tem->right;
tem->right = root;
return tem;
}
node *RR(node *root){
node *tem = root->right;
root->right = tem->left;
tem->left = root;
return tem;
}
node *LR(node *root){
node *A = root, *B = root->left, *C = root->left->right;// !!!
A->left = C->right;
B->right = C->left;
C->left = B;C->right = A;
return C;
}
node *RL(node *root){
node *A = root, *B = root->right, *C = root->right->left;// !!!
A->right = C->left;
B->left = C->right;
C->left = A;C->right = B;
return C;
}
node *insertAVL(node *root, int key){ //不需要node *&root
if(root == NULL){
root = new node();
root->key = key;
root->left = root->right = NULL;
return root;
}
else if(key >= root->key){
root->right = insertAVL(root->right, key); // !!!不是root = insertAVL(root->right, key);
if(getHeight(root->right) - getHeight(root->left) > 1){
if(key >= root->right->key)
root = RR(root);
else
root = RL(root);
}
}else{
root->left = insertAVL(root->left, key); // !!!不是root = insertAVL(root->left, key);
if(getHeight(root->left) - getHeight(root->right) > 1){
if(key < root->left->key)
root = LL(root);
else
root = LR(root);
}
}
return root;
}
void levelOrder(node *root){ //用于获得层次遍历
if(root == NULL)
return;
queue<node *> q;
q.push(root);
while(!q.empty()){
node *tem = q.front();
level.push_back(tem->key);
q.pop();
if(tem->left != NULL) q.push(tem->left);
if(tem->right != NULL) q.push(tem->right);
}
}
void dfs(node *root, int dep){ //用于判断是否为完全二叉树
if(root == NULL) return;// !!!
if(root->left == NULL && root->right == NULL){
maxDep = max(maxDep, dep);
return;
}
dfs(root->left, 2 * dep);
dfs(root->right, 2 * dep + 1);
}
int main(){
#ifdef ONLINE_JUDGE
#else
freopen("1.txt", "r", stdin);
#endif // ONLINE_JUDGE
cin>>N;
int num;
node *root = NULL;
for(int i = 0; i < N; i++){
cin>>num;
root = insertAVL(root, num);
}
levelOrder(root);
for(int i = 0; i < N; i++)
printf("%d%c", level[i], i == N-1 ? '\n':' ');
dfs(root, 1);
printf("%s", maxDep == N ? "YES":"NO"); //根据完全二叉树的性质 maxDep==N时即为完全二叉树
return 0;
}
4,解题过程
测试用例期间有些BUG,不过测试一次通过o(* ̄▽ ̄*)ブ