c语言实现平衡二叉树创建(AVL)

创建平衡二叉树

需要的辅助函数

  1. 创建树结点
  2. 计算每个节点高度
  3. 计算每个节点的平衡因子
  4. 插入新节点后对于出现的LL,RR,LR,RL型的子树处理问题
  5. 插入函数
  6. 构建一颗AVL平衡二叉树

本文章重点讲解第4个函数(在下文的step6,7,8,9)。

  • 什么树不是平衡二叉树?
  • 存在一个树节点的平衡因子绝对值大于1(平衡因子=左子树高度-右子树高度)

例:下图结点‘7‘的平衡因子为(左子树高度3-右子树高度1)=2
不是二叉平衡树

在这里插入图片描述
step1:定义树结点

typedef struct node
{
    
	int height;
	int data;
	struct node *lchild,*rchild;
}node;

step2:创建树结点

node *newNode(int v)
{
   
	node *Node=(node *)malloc(sizeof(node));
	Node->data=v;
	Node->height=1;
	Node->lchild=Node->rchild=NULL;
	return Node; 
}

step3:取得树结点高度

int getHeight(node *root)
{
    
	if(root==NULL) return 0;
	else{
   
		return root->height;
	}
}

step4:得到树结点的平衡因子

int getBalancedFactor(node *root)
{
   
	return getHeight(root->lchild)-getHeight(root->rchild);
}

step5:插入新结点后改变结点的高度(树结点的高度=max(左子树高度,右子树高度)+1)

void updateHeight(node *root){
   
	root->height=max(getHeight(root->lchild),getHeight(root->rchild))+1;
}

step6:调整RR型的不平衡子树(如下图,画的不好凑合看~)
在这里插入图片描述

void L(node *&root)
{
   
	node *temp=root->rchild;
	root->rchild=temp->lchild;
	temp->lchild=root;
	updateHeight(root);
	updateHeight(temp);
	root=temp;
}

step7:调整RR型的不平衡子树
在这里插入图片描述

void R(node *&
  • 8
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值