平衡二叉树(AVL树)

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

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值