您的位置:首页 > 编程语言 > Java开发

AVL树的java实现

2016-04-17 11:11 651 查看
package alogrithm;

public class AVLTree {
//使用一个嵌套类来表示平很二叉树的节点
private static class TreeNode{
public int val;
public TreeNode left;
public TreeNode right;
public int height;
//构造函数
public TreeNode(int element){
this(element,null,null);
}
//
public TreeNode(int element,TreeNode lt,TreeNode rt){
val=element;
left=lt;
right=rt;
height=0;
}
}
//计算节点高度
public int height(TreeNode t){

return t==null?-1:t.height;
}
//平衡二叉树的插入
public TreeNode insert(TreeNode t,int x){
if(t==null){
return new TreeNode(x);
}
if(t.val>x){
t.left=insert(t.left,x);
//插入左子树之后判断节点的平衡性
if(height(t.left)-height(t.right)==2){
if(x<t.left.val){
//左孩子的左子树,采用单旋转
t=rotateWithLeftChild(t);
}
else{
//左孩子的右子树,采用双旋转
t=doubleWithLeftChild(t);
}
}
}
else if(t.val<x){
t.right=insert(t.right,x);
//插入右子树之后判断节点的平衡性
if(height(t.right)-height(t.right)==2){
if(x>t.right.val){
//右孩子的右子树,采用单旋转
t=rotateWithRightChild(t);
}
else{
//右孩子的左子树,采用双旋转
t=doubleWithRightChild(t);
}
}
}
t.height=Math.max(height(t.left),height(t.right))+1;
return t;
}
//左单旋转
public TreeNode rotateWithLeftChild(TreeNode k2){
TreeNode k1=k2.left;
k2.left=k1.right;
k1.right=k2;
k2.height=Math.max(height(k2.left),height(k2.right))+1;
k1.height=Math.max(height(k1.left),k2.height)+1;
return k1;
}
//右单旋转
public TreeNode rotateWithRightChild(TreeNode k2){
TreeNode k1=k2.right;
k2.right=k1.left;
k1.left=k2;
k2.height=Math.max(height(k2.left),height(k2.right))+1;
k1.height=Math.max(k2.height,height(k1.right))+1;
return k1;
}
//左双旋转
public TreeNode doubleWithLeftChild(TreeNode k3){
k3.left=rotateWithRightChild(k3.left);
return rotateWithLeftChild(k3);
}
//右双旋转
public TreeNode doubleWithRightChild(TreeNode k3){
k3.right=rotateWithLeftChild(k3.right);
return rotateWithRightChild(k3);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: