#include <stdio.h>
#include<iostream>
#include <string.h>
#include <string>
#include <algorithm>
#include <map>
#include <vector>
#include <set>
#include <queue>
using namespace std;
typedef struct node {
int data, height;
node *left, *right;
}node;
int getHeight(node *root)
{
if (root == NULL)
return 0;
else
return root->height;
}
void upDateheight(node *&root)
{
root->height = max(getHeight(root->left), getHeight(root->right)) + 1;
}
int getBanlance(node *root)
{
return getHeight(root->left) - getHeight(root->right);
}
node *newNode(int data)
{
node *Node = new node;
Node->height = 1;
Node->left = Node->right = NULL;
Node->data = data;
return Node;
}
//右旋
void R(node *&root)
{
node *temp= root->left;
root->left = temp->right;
temp->right = root;
//更新节点的高度
upDateheight(root);
upDateheight(temp);
root = temp;
}
//左旋
void L(node *&root)
{
node *temp = root->right;
root->right = temp->left;
temp->left = root;
//更新节点的高度
upDateheight(root);
upDateheight(temp);
root = temp;
}
void insert(node *&root, int data)
{
if (root == NULL)
{
root = newNode(data);
return;
}
if (data < root->data)
{
insert(root->left, data);
upDateheight(root);
//调整
if (getBanlance(root) == 2)//如果左边太高了LL或LR
{
if (getBanlance(root->left) == -1)//LR型,应该先左旋,再右旋
{
L(root->left);
R(root);
}
else if (getBanlance(root->left) == 1)//LL型,应该右旋
{
R(root);
}
}
}
else
{
insert(root->right, data);
upDateheight(root);
//调整
if (getBanlance(root) == -2)//如果右边太高了,RR或RL
{
if (getBanlance(root->right) == -1)//RR型,应该左旋
{
L(root);
}
else if (getBanlance(root->right) == 1)//RL型,应该先右旋,再左旋
{
R(root->right);
L(root);
}
}
}
}
int search(node *root, int data)
{
if (root == NULL)
return 0;
if (root->data == data)
return 1;
else if (data < root->data)
return search(root->left, data);
else
return search(root->right, data);
}
int main()
{
int n,m, temp;
while (scanf("%d %d", &n,&m) != EOF)
{
node *root = NULL;
for (int i = 0; i < n; i++)
{
scanf("%d", &temp);
insert(root,temp);
}
//printf("%d\n", root->data);
for (int i = 0; i < m; i++)
{
scanf("%d", &temp);
if(i!=m-1)
printf("%d ", search(root, temp));
else
printf("%d\n", search(root, temp));
}
}
return 0;
}
CodeUP问题 A: 算法9-9~9-12:平衡二叉树的基本操作
最新推荐文章于 2022-02-09 23:02:36 发布