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); } }
相关文章推荐
- Java Web基础知识之Servlet(3):Session管理
- 快速排序(java 语言实现)
- Spring基础(一)——AOP&IoC
- 20145326 《Java程序设计》第7周学习总结
- 深入浅出Java并发包—锁机制(三)
- eclipse调试百度地图demo提示 230错误 Scode码校验失败
- 深入浅出Java并发包—读写锁ReentrantReadWriteLock原理分析(二)
- 安装eclipse的JRebel6.0.3的插件
- java基础(3)--java.lang.ClassLoader类的用法
- java冒泡排序
- 解密JVM GC
- Spring MVC整体处理流程
- 深入浅出Java并发包—锁机制(一)
- java中的缓存
- 【Java学习-J.160411.0.8】笔记7-Java第一个hello world学习
- struts2中拦截器实现的三种方式
- java native关键字
- 20145236 《Java程序设计》实验二实验报告
- 201301 JAVA题目0-1级
- 关于JDK和JRE