#include <iostream>
#include <cstdlib>
using namespace std;
typedef struct Node
{
int key;
struct Node *left;
struct Node *right;
int height;
}BTNode;
//初始化结点
BTNode* tree_node(int key)
{
struct Node* node=(BTNode*)malloc(sizeof(struct Node));
node->key=key;
node->right=NULL;
node->left=NULL;
node->height=1;
return node;
}
int max(int a,int b)
{
return (a>b)?a:b;
}
int height(struct Node *N)
{
if(N==NULL) return 0;
return N->height;
}
//ll形调整
BTNode* tree_ll_rotate(BTNode* t)
{
BTNode *x=t->left;
t->left=x->right;
x->right=t;
//更新树高
t->height = max(height(t->left), height(t->right)) + 1;
x->height = max(height(x->left), height(x->right)) + 1;
return x;
}
//rr形调整
BTNode* tree_rr_rotate(BTNode* t)
{
BTNode *x=t->right;
t->right=x->left;
x->left=t;
//更新树高
t->height = max(height(t->left), height(t->right)) + 1;
x->height = max(height(x->left), height(x->right)) + 1;
return x;
}
int tree_balance(BTNode *t)
{
if(t==NULL) return 0;
//bf=|左树-右树|
return height(t->left) - height(t->right);
}
//先序遍历
void preorder(struct Node*root)
{
//先左右
if(root)
{
cout<<root->key<<" ";
preorder(root->left);
preorder(root->right);
}
}
//中序遍历
void inorder(struct Node*root)
{
//左中右
if(root)
{
preorder(root->left);
cout<<root->key<<" ";
preorder(root->right);
}
}
//后序遍历
void postorder(struct Node*root)
{
//左右中
if(root)
{
preorder(root->left);
preorder(root->right);
cout<<root->key<<" ";
}
}
//插入创建结点
BTNode *tree_insert(BTNode *node,int key)
{
if(node==NULL) return tree_node(key);//新树第一个结点
//小于左边搜索 ,大于右边搜,等于直接插入
if(key<node->key) node->left= tree_insert(node->left,key);
else if(key>node->key) node->right= tree_insert(node->right,key);
else return node;
//计算height
node->height=max(height(node->left), height(node->right)) + 1;
int balance=tree_balance(node);
//ll
if(balance>1&&node->left->key>key) return tree_ll_rotate(node);
//lr
if(balance>1&&node->left->key<key)
{
//先l-rr
node->left =tree_rr_rotate(node->left);
return tree_ll_rotate(node);
}
//rr
if(balance<-1&&key>node->right->key) return tree_rr_rotate(node);
//rl
if(balance<-1&&key<node->right->key)
{
node->right =tree_ll_rotate(node->right);
return tree_rr_rotate(node);
}
return node;
}
int main()
{
BTNode *root=NULL;
//插入数据
root=tree_insert(root,2);
root=tree_insert(root,1);
root=tree_insert(root,0);
root=tree_insert(root,3);
root=tree_insert(root,4);
root=tree_insert(root,4);
root=tree_insert(root,5);
root=tree_insert(root,6);
root=tree_insert(root,9);
root=tree_insert(root,8);
root=tree_insert(root,7);
cout<<"前序遍历的结果:";
preorder(root);
cout<<endl;
cout<<"中序遍历的结果:";
inorder(root);
cout<<endl;
cout<<"后序遍历的结果:";
postorder(root);
cout<<endl;
return 0;
}
平衡二叉树的基本操作实现
于 2024-08-08 23:55:09 首次发布