算法笔记练习 题解合集
题目
题目描述
平衡二叉树又称AVL树,它是一种具有平衡因子的特殊二叉排序树。平衡二叉树或者是一棵空树,或者是具有以下几条性质的二叉树:
- 若它的左子树不空,则左子树上所有结点的值均小于它的根节点的值;
- 若它的右子树不空,则右子树上所有结点的值均大于它的根节点的值;
- 它的左右子树也分别为平衡二叉树,且左子树和右子树的深度之差的绝对值不超过1。
若将二叉树上结点的平衡因子定义为该结点的左子树深度减去它的右子树的深度,则平衡二叉树上的所有结点的平衡因子只可能为-1、0和1。只要二叉树上有一个结点的平衡因子的绝对值大于1,则这棵二叉树就是不平衡的。
通过平衡二叉树的性质不难得知,其插入、删除、查询都操作的时间复杂度均为O(log2n)。
维持平衡二叉树性质的操作可以被称为旋转。其中平衡二叉树的右旋处理可以描述如下:
而其左旋处理与右旋正好相反,可以描述如下:
在本题中,读入一串整数,首先利用这些整数构造一棵平衡二叉树。另外给定多次查询,利用构造出的平衡二叉树,判断每一次查询是否成功。
输入
输入的第一行包含2个正整数n和k,分别表示共有n个整数和k次查询。其中n不超过500,k同样不超过500。
第二行包含n个用空格隔开的正整数,表示n个整数。
第三行包含k个用空格隔开的正整数,表示k次查询的目标。
输出
只有1行,包含k个整数,分别表示每一次的查询结果。如果在查询中找到了对应的整数,则输出1,否则输出0。
请在每个整数后输出一个空格,并请注意行尾输出换行。
样例输入
8 3
1 3 5 7 8 9 10 15
9 2 5
样例输出
1 0 1
思路
思路和 AVL 树的代码参考算法笔记 P319,我只是把代码照搬了一遍。
代码
#include <iostream>
using namespace std;
struct node {
int v, height;
node *lchild, *rchild;
};
node* newNode(int v) {
node *Node = new node;
Node->v = v;
Node->height = 1;
Node->lchild = Node->rchild = NULL;
return Node;
}
int getHeight(node* root) {
if (root == NULL) return 0;
return root->height;
}
int getBalanceFactor(node* root) {
return getHeight(root->lchild) - getHeight(root->rchild);
}
void updateHeight(node *root) {
root->height = max(getHeight(root->lchild), getHeight(root->rchild)) + 1;
}
void search(node* root, int x) {
if (root == NULL) {
printf("0 ");
return;
}
if (x == root->v) {
printf("1 ");
} else if (x < root->v) {
search(root->lchild, x);
} else {
search(root->rchild, x);
}
}
void L(node* &root) {
node *temp = root->rchild;
root->rchild = temp->lchild;
temp->lchild = root;
updateHeight(root);
updateHeight(temp);
root = temp;
}
void R(node* &root) {
node *temp = root->lchild;
root->lchild = temp->rchild;
temp->rchild = root;
updateHeight(root);
updateHeight(temp);
root = temp;
}
void insert(node* &root, int v) {
if (root == NULL) {
root = newNode(v);
return;
}
if (v < root->v) {
insert(root->lchild, v);
updateHeight(root);
if (getBalanceFactor(root) == 2) {
if (getBalanceFactor(root->lchild) == 1) {
R(root);
} else if (getBalanceFactor(root->lchild) == -1) {
L(root->lchild);
R(root);
}
}
} else {
insert(root->rchild, v);
updateHeight(root);
if (getBalanceFactor(root) == -2) {
if (getBalanceFactor(root->rchild) == -1) {
L(root);
} else if (getBalanceFactor(root->rchild) == 1) {
R(root->rchild);
L(root);
}
}
}
}
node* Create(int data[], int n) {
node* root = NULL;
for (int i = 0; i < n; ++i)
insert(root, data[i]);
return root;
}
int main() {
int n, k, input;
while (scanf("%d%d", &n, &k) != EOF) {
int data[n];
for (int i = 0; i < n; ++i)
scanf("%d", &data[i]);
node *root = Create(data, n);
for (int i = 0; i < k; ++i) {
scanf("%d", &input);
search(root, input);
}
putchar('\n');
}
return 0;
}