数据结构实验之查找二:平衡二叉树
Time Limit: 400MS
Memory Limit: 65536KB
Problem Description
根据给定的输入序列建立一棵平衡二叉树,求出建立的平衡二叉树的树根。
Input
输入一组测试数据。数据的第1行给出一个正整数N(n <= 20),N表示输入序列的元素个数;第2行给出N个正整数,按数据给定顺序建立平衡二叉树。
Output
输出平衡二叉树的树根。
Example Input
5 88 70 61 96 120
Example Output
70
#include <bits/stdc++.h>
using namespace std;
struct node
{
int data;
int d;
struct node *l, *r;
};
int max(int x, int y)
{
return x > y?x:y;
}
int deep(struct node *head)
{
if(head==NULL)
{
return -1;
}
else
{
return head->d;
}
}
struct node *LL(struct node *head)
{
struct node *q;
q = head -> l;
head -> l = q -> r;
q -> r = head;
head -> d = max(deep(head->l), deep(head->r) )+1;
q->d = max(deep(q->l), deep(q->r)) +1;
return q;
};
struct node *RR(struct node *head)
{
struct node *q;
q = head -> r;
head -> r = q -> l;
q -> l = head;
head -> d = max(deep(head->l), deep(head->r) )+1;
q->d = max(deep(q->l), deep(q->r)) +1;
return q;
};
struct node *LR(struct node *root)
{
root -> l = RR(root->l);
return LL(root);
};
struct node *RL(struct node *root)
{
root -> r = LL(root->r);
return RR(root);
};
struct node *creat(struct node *root, int x)
{
if(root == NULL)
{
root = new node;
root -> data = x;
root->l = root->r = NULL;
}
else if(x < root->data)
{
root -> l = creat(root->l, x);
if(deep(root->l) -deep(root->r) > 1)
{
if(x < root->l->data)
{
root = LL(root);
}
else
{
root = LR(root);
}
}
}
else
{
root ->r = creat(root->r, x);
if(deep(root->r) - deep(root->l) > 1)
{
if(x > root->r->data)
{
root = RR(root);
}
else
{
root = RL(root);
}
}
}
root -> d = max(deep(root->l), deep(root->r)) +1;
return root;
};
int main()
{
int n;
int x, i;
cin >> n;
struct node *root = NULL;
for(i = 0; i < n; i++)
{
cin >> x;
root = creat(root, x);
}
cout << root->data << endl;
return 0;
}

本文介绍了一种根据给定序列构建平衡二叉树的方法,并提供了完整的C++代码实现。通过该方法可以有效地维持二叉树的平衡状态,确保树的高度保持在较低水平,从而提高搜索效率。
3416

被折叠的 条评论
为什么被折叠?



