Sha256: 363bd2987f189a8bd4bbbf920fd9f6b8d086ee7199838e501ea913894e592fc4

Contents?: true

Size: 890 Bytes

Versions: 396

Compression:

Stored size: 890 Bytes

Contents

local BinarySearchTree = {}
BinarySearchTree.__index = BinarySearchTree

function BinarySearchTree:new(value)
  return setmetatable({
    value = value
  }, self)
end

function BinarySearchTree:from_list(list)
  assert(#list > 0)
  local tree = BinarySearchTree:new(list[1])
  for i = 2, #list do
    tree:insert(list[i])
  end
  return tree
end

function BinarySearchTree:values()
  return coroutine.wrap(function()
    if self.left then
      for v in self.left:values() do coroutine.yield(v) end
    end
    coroutine.yield(self.value)
    if self.right then
      for v in self.right:values() do coroutine.yield(v) end
    end
  end)
end

function BinarySearchTree:insert(value)
  local side = value > self.value and 'right' or 'left'
  if self[side] then
    self[side]:insert(value)
  else
    self[side] = BinarySearchTree:new(value)
  end
  return self
end

return BinarySearchTree

Version data entries

396 entries across 396 versions & 1 rubygems

Version Path
trackler-2.2.1.139 tracks/lua/exercises/binary-search-tree/example.lua
trackler-2.2.1.138 tracks/lua/exercises/binary-search-tree/example.lua
trackler-2.2.1.137 tracks/lua/exercises/binary-search-tree/example.lua
trackler-2.2.1.136 tracks/lua/exercises/binary-search-tree/example.lua
trackler-2.2.1.135 tracks/lua/exercises/binary-search-tree/example.lua
trackler-2.2.1.134 tracks/lua/exercises/binary-search-tree/example.lua
trackler-2.2.1.133 tracks/lua/exercises/binary-search-tree/example.lua
trackler-2.2.1.132 tracks/lua/exercises/binary-search-tree/example.lua
trackler-2.2.1.131 tracks/lua/exercises/binary-search-tree/example.lua
trackler-2.2.1.130 tracks/lua/exercises/binary-search-tree/example.lua
trackler-2.2.1.129 tracks/lua/exercises/binary-search-tree/example.lua
trackler-2.2.1.128 tracks/lua/exercises/binary-search-tree/example.lua
trackler-2.2.1.127 tracks/lua/exercises/binary-search-tree/example.lua
trackler-2.2.1.126 tracks/lua/exercises/binary-search-tree/example.lua
trackler-2.2.1.125 tracks/lua/exercises/binary-search-tree/example.lua
trackler-2.2.1.124 tracks/lua/exercises/binary-search-tree/example.lua
trackler-2.2.1.123 tracks/lua/exercises/binary-search-tree/example.lua
trackler-2.2.1.122 tracks/lua/exercises/binary-search-tree/example.lua
trackler-2.2.1.121 tracks/lua/exercises/binary-search-tree/example.lua
trackler-2.2.1.120 tracks/lua/exercises/binary-search-tree/example.lua