平衡二叉树定义(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);