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.180 tracks/lua/exercises/binary-search-tree/example.lua
trackler-2.2.1.179 tracks/lua/exercises/binary-search-tree/example.lua
trackler-2.2.1.178 tracks/lua/exercises/binary-search-tree/example.lua
trackler-2.2.1.177 tracks/lua/exercises/binary-search-tree/example.lua
trackler-2.2.1.176 tracks/lua/exercises/binary-search-tree/example.lua
trackler-2.2.1.175 tracks/lua/exercises/binary-search-tree/example.lua
trackler-2.2.1.174 tracks/lua/exercises/binary-search-tree/example.lua
trackler-2.2.1.173 tracks/lua/exercises/binary-search-tree/example.lua
trackler-2.2.1.172 tracks/lua/exercises/binary-search-tree/example.lua
trackler-2.2.1.171 tracks/lua/exercises/binary-search-tree/example.lua
trackler-2.2.1.170 tracks/lua/exercises/binary-search-tree/example.lua
trackler-2.2.1.169 tracks/lua/exercises/binary-search-tree/example.lua
trackler-2.2.1.167 tracks/lua/exercises/binary-search-tree/example.lua
trackler-2.2.1.166 tracks/lua/exercises/binary-search-tree/example.lua
trackler-2.2.1.165 tracks/lua/exercises/binary-search-tree/example.lua
trackler-2.2.1.164 tracks/lua/exercises/binary-search-tree/example.lua
trackler-2.2.1.163 tracks/lua/exercises/binary-search-tree/example.lua
trackler-2.2.1.162 tracks/lua/exercises/binary-search-tree/example.lua
trackler-2.2.1.161 tracks/lua/exercises/binary-search-tree/example.lua
trackler-2.2.1.160 tracks/lua/exercises/binary-search-tree/example.lua