summaryrefslogtreecommitdiff
path: root/lib/tree.rb
blob: 95ac18f5556b85af201cd30f7ed4fb217729e357 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
class Tree
  attr_accessor :value, :left, :right

  def initialize(value, left: nil, right: nil)
    @value = value
    @left = left
    @right = right
  end

  def to_a
    [value, left&.to_a, right&.to_a]
  end

  def print(prefix = '', tail = true)
    puts(prefix + (tail ? "└── " : "├── ") + value.to_s)

    prefix = prefix + (tail ? "    " : "│   ")
    right.print(prefix, false) if right
    left.print(prefix, false) if left
  end

  def to_h
    { value: value, left: left&.to_h, right: right&.to_h }
  end

  def to_sexpression(tree)
    return "()" if tree.nil?
    "(#{tree.value}#{to_sexpression(tree.left)},#{to_sexpression(tree.right)})"
  end

  def to_s
    to_sexpression(self)
  end

  def self.build_from(hash)
    return nil if hash.nil?
    Tree.new(hash[:value], left: build_from(hash[:left]), right: build_from(hash[:right]))
  end
end