平衡二叉树实战
题目描述: 输入一系列节点权值,按输入顺序构成平衡二叉树,输出根节点的权值。
什么是平衡二叉树?
平衡二叉树是特殊的二叉排序树,权值左 < 权值根 < 权值右 ,且它的每个节点的左右子树高度之差不大于1,左右子树的高度差为平衡因子,平衡因子只能为1、-1、0。
如何构成平衡二叉树?
顺序插入节点,当发现不满足平衡二叉树的性质,则对树进行旋转。旋转规则如下:
1)LL(右旋)。在节点A的左孩子的左子树插入新节点导致其不平衡,需要向右旋转,用A的左孩子B代替A,A向右旋转为B的右孩子。而B的原右子树为A的左子树。
对照代码理解其左右旋转,右旋代码如下:
void R(node* &root){
node* t=root->lchild;
root->lchild=t->rchild;
t->rchild=root;
updateHeight(root);
updateHeight(t);
root=t;
}
2)RR(左旋)。在节点A的右孩子的右子树插入新节点导致其不平衡,需要向左旋转,用A的右孩子B代替A,A向左旋为B的左孩子。而B的原左子树成为A的右子树。
左旋代码如下:
void L(node* &root){
node* t=root->rchild;
root->rchild=t->lchild;
t->lchild=root;
updateHeight(root);
updateHeight(t);
root=t;
}
3)RL(先右旋后左旋)。在节点A的右孩子的左子树插入新的节点导致其不平衡,需要先将A的右孩子B右旋,再将A左旋。
4)LR(先左旋后右旋)。在节点A的左孩子的右子树插入新的节点导致其不平衡,需要先将A的左孩子B进行左旋,再讲A右旋。
依次输入88、70、61、96、120、09、65,构造平衡二叉树,如下图所示:
运行截图:
代码如下:
#include<iostream>
#include<algorithm>
using namespace std;
struct node{
int v,height; //v为权值,height为当前节点高度
node* lchild, *rchild;
}*root;
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){ //获取以root为根的树高
if(root==NULL) return 0;
return root->height;
}
// 树高为左右子树中最大高度+1
void updateHeight(node* root){
root->height=max(getHeight(root->lchild),getHeight(root->rchild))+1;
}
//计算节点的平衡因子:左子树高度-右子树高度
int getBalance(node* root){
return getHeight(root->lchild) - getHeight(root->rchild);
}
//左旋
void L(node* &root){
node* t=root->rchild;
root->rchild=t->lchild;
t->lchild=root;
updateHeight(root);
updateHeight(t);
root=t;
}
//右旋
void R(node* &root){
node* t=root->lchild;
root->lchild=t->rchild;
t->rchild=root;
updateHeight(root);
updateHeight(t);
root=t;
}
//插入节点进行旋转
void insert(node* &root,int v){
if(root==NULL){
root=newNode(v);
return;
}
if(v<root->v){ //权值小于根节点
insert(root->lchild,v);
updateHeight(root);
if(getBalance(root)==2){ //不平衡要讨论哪种情况
if(getBalance(root->lchild)==1){ //LL型
R(root);
}else if(getBalance(root->lchild)==-1){ // LR型
L(root->lchild);
R(root);
}
}
}else{ // 权值大于根节点
insert(root->rchild,v);
updateHeight(root);
if(getBalance(root)==-2){
if(getBalance(root->rchild)==-1){ //LL型
L(root);
}else if(getBalance(root->rchild)==1){ // LR型
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]);
}
cout<<root;
return root;
}
int main(){
int n;
cin>>n;
for(int i=0;i<n;i++){
int x;
cin>>x;
insert(root,x);
}
cout<<root->v;
return 0;
}