逐步构建一个平衡二叉树模版

转自晴神宝典

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 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){//LL型,直接右旋
				R(root);
			}
			else if(getBalanceFactor(root->lchild) == -1){//LR型,先左子树左旋,然后右旋
				L(root->lchild);
				R(root);
			}
		}
	}
	else{
		insert(root->rchild,v);
		updateHeight(root);
		if(getBalanceFactor(root) == -2){
			if(getBalanceFactor(root->rchild) == -1){//RR型直接左旋
				L(root);
			}
			else if(getBalanceFactor(root->rchild) == 1){//RL型先右子树右旋,然后左旋
				R(root->rchild);
				L(root);
			}
		}    	
	}
}
node* Creat(int data[],int n){
	node* root = NULL;
	for(int i=0;i<n;i++){
		insert(root,data[i]);
	}
	return root;
}
    原文作者:平衡二叉树
    原文地址: https://blog.csdn.net/Line290/article/details/54413672
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞