题目链接
思路?
①还是参考《算法笔记的AVL部分,做了一些代码上的简化(相比于另一道题
②完全二叉树的判断参考于这里
代码
using namespace std;
#include<bits/stdc++.h>
struct node {
int data;
node* left, * right;
node(int d = 0) :data(d), left(NULL), right(NULL) {}
};
int getheight(node* n) {
return n == NULL ? 0 : max(getheight(n->left), getheight(n->right)) + 1;
}
void L(node*& n) {
node* temp = n->right;
n->right = temp->left;
temp->left = n;
n = temp;
}
void R(node*& n) {
node* temp = n->left;
n->left = temp->right;
temp->right = n;
n = temp;
}
void insert(node*& n, int d) {
if (n == NULL) {
n = new node(d);
return;
}
if (d < n->data) {
insert(n->left, d);
if (getheight(n->left)-getheight(n->right)==2) {
if (d<n->left->data) R(n);
else L(n->left), R(n);
}
}
else if (d > n->data) {
insert(n->right, d);
if (getheight(n->left) - getheight(n->right) == -2) {
if (d>n->right->data) L(n);
else R(n->right), L(n);
}
}
}
bool traversal(node* n) {
bool leaf = false, flag = true;
queue<node*>waiting;
waiting.push(n);
while (!waiting.empty()) {
node* temp = waiting.front();
waiting.pop();
if (waiting.empty() && !temp->left && !temp->right)cout << temp->data << endl;
else cout << temp->data << " ";
if ((leaf && (temp->left || temp->right)) || (!temp->left && temp->right)) flag = false;
if (temp->left)waiting.push(temp->left);
if (temp->right)waiting.push(temp->right);
if ((!temp->right && !temp->left) || (temp->left && !temp->right))leaf = true;
}
return flag;
}
int main() {
int n, temp;
cin >> n;
node* root = NULL;
for (int i = 0; i < n; i++) {
cin >> temp;
insert(root, temp);
}
if (traversal(root))cout << "YES";
else cout << "NO";
return 0;
}
啊
昨天做了人生第一道AVL,而今天这道…好像这就是甲级题库里最后一道avl了___*(  ̄皿 ̄)/#____giao