Advertisement
AhmedGhazaly

AVLTree

Jul 16th, 2017
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 2.25 KB | None | 0 0
  1.  
  2. class node(val data : Int ){
  3.     var hieght:Int=0
  4.     var left:node?=null
  5.     var right:node?=null
  6. }
  7. class tree(){
  8.     fun getHeight(root:node?):Int{
  9.         if (root==null)return 0;
  10.         return root.hieght
  11.     }
  12.     fun setHeight(root:node):Int{
  13.         return Math.max(getHeight(root.left),getHeight(root.right))+1
  14.     }
  15.     fun rotateLeft(root: node):node{
  16.         var t:node=root.right!!
  17.         root.right=root.right?.left
  18.         t.left=root;
  19.         t.hieght=setHeight(t)
  20.         root.hieght=setHeight(root)
  21.         return t
  22.     }
  23.     fun rotateRight(root: node):node{
  24.         var t:node=root.left!!
  25.         root.left=root.left?.right
  26.         t.right=root;
  27.         t.hieght=setHeight(t)
  28.         root.hieght=setHeight(root)
  29.         return t
  30.     }
  31.  
  32.     fun insert(root:node?,data: Int):node{
  33.         //normal insert
  34.         var r:node?=root
  35.         if (r==null){
  36.             r=node(data)
  37.         }else if(data>r.data){
  38.             r.right=insert(r.right,data)
  39.         }else {
  40.             r.left=insert(r.left,data)
  41.         }
  42.         //balancing the tree
  43.         var d=getHeight(r?.left)-getHeight(r?.right)
  44.         if(d>1){//then its not balnaced
  45.             if(getHeight(r?.left?.left)>=getHeight(r?.left?.right))r=rotateRight(r!!)
  46.             else{
  47.                 rotateLeft(r!!)
  48.                 rotateRight(r!!)
  49.             }
  50.         }else if(d<-1){//then it's not balanced
  51.             if(getHeight(r?.right?.right)>=getHeight(r?.right?.left))r=rotateLeft(r!!)
  52.             else{
  53.                 r=rotateRight(r!!)
  54.                 r=rotateLeft(r!!)
  55.             }
  56.         }
  57.         //updating the hight
  58.         r.hieght=setHeight(r)
  59.         return r
  60.     }
  61.     fun search(root:node?, data:Int):Boolean{
  62.         if (root==null)return false
  63.         if(root.data==data)return true
  64.         else if(data>root.data)return search(root.right,data)
  65.         else return search(root.left,data)
  66.     }
  67.  
  68. }
  69.  
  70. fun main(args: Array<String>) {
  71.     var avl=tree()
  72.     var tree:node=node(9)
  73.     tree=avl.insert(tree,8)
  74.     tree=avl.insert(tree,7)
  75.     tree=avl.insert(tree,6)
  76.     tree=avl.insert(tree,5)
  77.     tree=avl.insert(tree,4)
  78.     tree=avl.insert(tree,3)
  79.  
  80.  
  81.     println(avl.search(tree,5))
  82.     println(avl.getHeight(tree))
  83.  
  84.  
  85. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement