js实现平衡二叉树

平衡二叉树定义(AVL):它或者是一颗空树,或者具有以下性质的二叉排序树:它的左子树和右子树的深度之差(平衡因子)的绝对值不超过1,且它的左子树和右子树都是一颗平衡二叉树
平衡二叉树必须是二叉搜索树


var Node=function(key)
{
	this.key=key;
	this.lchild=null;
	this.rchild=null;
	this.height=1;//平衡因子
}

var root = null;//根节点

getRoot=function(){return root;}

function max(a,b){return (a>b)?a:b;}
function nodeHeight(node)
{
	if(node===null)
		return
	return node.height
}
function LLRotate(node)
{
	let x=new Node(null);
	x=node.lchild;
	node.lchild=x.rchild;
	x.rchild=node;
	node.height=max(nodeHeight(node.lchild),nodeHeight(node.rchild))+1;
	x.height=max(nodeHeight(x.lchild),nodeHeight(x.rchild))+1;
	return x;
}
function RRRotate(node)
{
	let x=new Node(null);
	x=node.rchild;
	node.rchild=x.lchild;
	x.lchild=node;
	node.height=max(nodeHeight(node.lchild),nodeHeight(node.rchild))+1;
	x.height=max(nodeHeight(x.lchild),nodeHeight(x.rchild))+1;
	return x;
}
function insertNode(node,key)
{
	if(node===null)
		return new Node(key);
	if(node.key>key)
		node.lchild=insertNode(node.lchild,key);
	else if(node.key<key)
		node.rchild=insertNode(node.rchild,key);
	else
		return node;
	node.height=max(nodeHeight(node.lchild),nodeHeight(node.rchild))+1;
	let balance=getBalance(node);
	//LL型
	if(balance>1&&key<node.lchild.key)
		return LLRotate(node);
	//RR型
	if(balance<-1&&key>node.rchild.key)
		return RRRotate(node);
	//LR型
	if(balance>1&&key>node.lchild.key)
	{
		node.lchild=RRRotate(node.lchild);
		return LLRotate(node);
	}
	//RL型
	if(balance<-1&&key<node.rchild.key)
	{
		node.rchild=LLRotate(node.rchild);
		return RRRotate(node);
	}
	return node;
}
function getBalance(node)
{
	if(node===null)
		return 0;
	return nodeHeight(node.lchild)-nodeHeight(node.rchild);
}
function printLog(item)
{
	console.log(item)
}
function preOrderTraverse(node,printLog)
{
	if(node!=null)
	{
		printLog(node.key);
		this.preOrderTraverse(node.lchild,printLog);
		this.preOrderTraverse(node.rchild,printLog);
	}
}
var arr=[2,1,0,3,4,4,5,6,9,8,7];
var root=new Node();
arr.forEach(item=>{
	root=insertNode(root,item)
})
preOrderTraverse(root);
	
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值