您的位置:首页 > 其它

平衡二叉树(AVL树)

2018-02-28 16:20 423 查看
平衡二叉树(AVL树),是一种有序树,因为普通的二叉树如果添加的节点有序,查询效率会与数组无异,而AVL树改变了它的弊端,会实时调整树的高度,使它左右子树的树高之差的绝对值不会大于1。下面给出使用java代码完成的AVL树:import java.util.LinkedList;
import java.util.Queue;

class AVLTree {
private int n; //数据域
private int balance = 0; //该树根的平衡度
private AVLTree l; //左子树
private AVLTree r; //右子树

public AVLTree(int n) {
this.n = n;
}

/**
* 因为每添加一个需要调整数的结构,有可能改变树根,因此
* 需要返回更新后的树根
*/
public AVLTree add(AVLTree x) {
AVLTree root = this;
if (x.n < n) {
if (l == null)
l = x;

else
l = l.add(x);
} else {
if (r == null)
r = x;

else
r = r.add(x);
}
calcuBalance(); //计算该树根平衡度
if (balance > 1) {
if (l.balance > 0) {
root = adjustLL(); //LL型调整
} else {
root = adjustLR(); //LR型调整
}
}
if (balance < -1) {
if (l==null || l.balance < 0) {
root = adjustRR(); //RR型调整
} else {
root = adjustRL(); //RL型调整
}
}
calcuBalance();
return root;
}
//RL型调整
private AVLTree adjustRL() {
r = r.adjustLL();
return adjustRR();
}
//LR型调整
private AVLTree adjustLR() {
l = l.adjustRR();
return adjustLL();
}
//RR型调整
private AVLTree adjustRR() {
AVLTree root = r;
r = root.l;
root.l = this;
return root;
}
//LL型调整
private AVLTree adjustLL() {
AVLTree root = l;
l = root.r;
root.r = this;
return root;
}
//计算平衡度
private void calcuBalance() {
int hl, hr;
if (l == null)
hl = 0;
else
hl = l.getHeight();
if (r == null)
hr = 0;
else
hr = r.getHeight();
balance = hl - hr;
}
//计算树高
public int getHeight() {
int hl, hr;
if (l == null)
hl = 0;
else
hl = l.getHeight();
if (r == null)
hr = 0;
else
hr = r.getHeight();
return Math.max(hl, hr) + 1;
}
//中序遍历
public void midTravel() {
if (l != null) {
l.midTravel();
}
System.out.print(n + " ");
if (r != null) {
r.midTravel();
}
}
//层序遍历
public void lelTravel() {
Queue<AVLTree> que = new LinkedList<AVLTree>();
AVLTree root = this;
que.add(root);
while(!que.isEmpty()) {
root = que.remove();
System.out.print(root.n + " ");
if(root.l != null) {
que.add(root.l);
}
if(root.r != null) {
que.add(root.r);
}
}

}

}
public class AVLTreeTest {

public static void main(String[] args) {
AVLTree at = new AVLTree(1);
at = at.add(new AVLTree(3));
at = at.add(new AVLTree(5));
at = at.add(new AVLTree(7));
at = at.add(new AVLTree(9));
at.lelTravel();
System.out.println();
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: