type 'a avl = Empty | Node of int * 'a avl * 'a * 'a avl
                            
let depth tree = 
    match tree with
        Node (d, _, _, _) -> d
      | Empty -> 0

let value tree = 
    match tree with
        Node (_, _, x, _) -> x
      | Empty -> failwith "Impossible"
                   

 let balanceLL node = 
    match node with 
        (Node (d, Node (lmax, ll, xl, rl), x, r)) ->
          let rmax = max (depth rl) (depth r) + 1 
          in let cmax = max rmax (depth ll) + 1
          in Node (cmax, ll, xl, Node (rmax, rl, x, r))
      | _ -> failwith "Impossible"

  let balanceLR node =
    match node with 
        (Node (d, Node (dl, ll, y, Node (dlr, lrl, z, lrr)), x, r)) -> 
          let lmax = max (depth ll) (depth lrl) + 1
          in let rmax = max (depth lrr) (depth r) + 1
          in let cmax = max lmax rmax + 1
          in Node (cmax, Node (lmax, ll, y, lrl), z, Node (rmax, lrr, x, r))
      | _ -> failwith "Impossible"

  let balanceRR node = match node with
      (Node (d, l, x, Node (dr, lr, xr, rr))) ->
        let lmax = max (depth l) (depth lr) + 1
        in let cmax = max lmax (depth rr) + 1
        in Node (cmax, Node (lmax, l, x, lr), xr, rr)
    | _ -> failwith "Impossible"

  let balanceRL node =
    match node with 
        (Node (d, l, x, Node (dr, Node (drl, rll, z, rlr), y, rr))) ->
          let lmax = max (depth l) (depth rll) + 1
          in let rmax = max (depth rlr) (depth rr) + 1
          in let cmax = max lmax rmax + 1
          in Node (cmax, Node (lmax, l, x, rll), z, Node (rmax, rlr, y, rr)) 
    | _ -> failwith "Impossible"
             
(* alĂ­nea 8 *)
                                
  let rec insert comp  e t = 
    match t with
        Node (_, l, x, r) ->
          (match comp e x with
               -1 -> 
                 let insL = insert comp e l
                 in let dl = depth insL
                 in let dr = depth r
                 in let bal = dl - dr
                 in
                   if bal <> 2
                   then Node ((max dr dl) + 1, insL, x, r)
                   else if e < value l
                   then balanceLL (Node (dl + 1, insL, x, r))
                   else if e > value l
                   then balanceLR (Node (dl + 1, insL, x, r))
                   else t
             | 0 -> t
             | _ -> 
                 let insR = insert comp e r
                 in let dr = depth insR
                 in let dl = depth l
                 in let bal = dl - dr
                 in
                   if bal <> -2
                   then Node ((max dr dl) + 1, l, x, insR)
                   else if e > value r
                   then balanceRR (Node (dr + 1, l, x, insR))
                   else if e < value r
                   then balanceRL (Node (dr + 1, l, x, insR))
                   else t)
      | Empty -> Node (1, Empty, e, Empty)
      

This document was generated using caml2html