Skip to content

Instantly share code, notes, and snippets.

@OnurGumus
Created September 27, 2019 10:50
Show Gist options
  • Save OnurGumus/a590da51a48b1f927deac0067e19b747 to your computer and use it in GitHub Desktop.
Save OnurGumus/a590da51a48b1f927deac0067e19b747 to your computer and use it in GitHub Desktop.
Sedgewick binary tree
// Write code or load a sample from sidebar
open Fable
open Fable.Core
open Fable.Core.JS
[<AllowNullLiteralAttribute>]
type Node<'Key , 'Value when 'Key :> System.IComparable<'Key>>(key: 'Key, value : 'Value , N : int) =
member _.Key = key
member val Value = value with get, set
member val N = N with get, set
member val Left : Node<'Key,'Value> = Unchecked.defaultof<_> with get, set
member val Right : Node<'Key,'Value> = Unchecked.defaultof<_> with get, set
type BinarySearchST<'Key, 'Value when 'Key :> System.IComparable<'Key>> () =
[<DefaultValue>] val mutable root : Node<'Key,'Value>
member this.Size() = this.Size(this.root)
member this.Size(x : Node<'Key,'Value>)=
if x |> isNull then 0
else x.N
member private this.Put (x : Node<'Key,'Value>, key:'Key , value:'Value) =
if x |> isNull then Node( key , value, 1)
else
let cmp = key.CompareTo(x.Key)
if cmp < 0 then x.Left <- this.Put(x.Left, key, value)
else if cmp > 0 then x.Right <- this.Put(x.Right, key, value)
else x.Value <- value;
x.N <- this.Size(x.Left) + this.Size(x.Right) + 1
x
member this.Put(key : 'Key, value : 'Value)
= this.root <- this.Put(this.root, key, value)
member this.Get(key : 'Key) =
this.Get(this.root,key)
member this.Get(x : Node<'Key,'Value>, key : 'Key) : 'Value =
if x |> isNull then Unchecked.defaultof<'Value>
else
let cmp = key.CompareTo(x.Key)
if cmp < 0 then this.Get(x.Left, key);
else if (cmp > 0) then this.Get(x.Right, key)
else x.Value
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment