Advertisement
tomuwhu

Keresőfa

Feb 20th, 2020
151
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. class OSet {
  2.     has( key ) {
  3.         return !this.ik( this.root, key )
  4.     }
  5.     ik(p, key) {
  6.         if (p) {
  7.             if (p.key === key) return false
  8.             else {
  9.                 this.up = p
  10.                 if ( p.key < key ) {
  11.                     this.rd = true
  12.                     return this.ik( p.r, key )
  13.                 } else {
  14.                     this.rd = false
  15.                     return this.ik( p.l, key )
  16.                 }
  17.             }
  18.         } else return { key }
  19.     }
  20.     add( key ) {
  21.         if ( this.root ) {
  22.             var uo
  23.             if ( uo = this.ik( this.root, key )) {
  24.                 if ( this.rd ) this.up.r = uo
  25.                 else this.up.l = uo
  26.                 return true
  27.             } else return false
  28.         } else {
  29.             this.root = { key }
  30.         }
  31.         delete this.up
  32.         delete this.rd
  33.     }
  34.     ib( p, f ) {
  35.         if ( p ) {
  36.             this.ib( p.l, f )
  37.             f( p.key, this.i++ )
  38.             this.ib( p.r, f )
  39.         }
  40.     }
  41.     forEach( f ) {
  42.         this.i = 0
  43.         this.ib( this.root, f )
  44.         delete this.i
  45.     }
  46. }
  47.  
  48. const m = new OSet()
  49.  
  50. const t = [8, 4, 12, 16, 14, 18, 2, 12, 1, 6, 5, 7]
  51. t.forEach( v => m.add( v ) )
  52.  
  53. console.log( m.has( 4 ), m.has( 3 ) )
  54.  
  55. m.forEach( console.log )
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement