master
 1class Tree
 2  attr_accessor :value, :left, :right
 3
 4  def initialize(value, left: nil, right: nil)
 5    @value = value
 6    @left = left
 7    @right = right
 8  end
 9
10  def to_a
11    [value, left&.to_a, right&.to_a]
12  end
13
14  def print(prefix = '', tail = true)
15    puts(prefix + (tail ? "└── " : "├── ") + value.to_s)
16
17    prefix = prefix + (tail ? "    " : "")
18    right.print(prefix, false) if right
19    left.print(prefix, false) if left
20  end
21
22  def to_h
23    { value: value, left: left&.to_h, right: right&.to_h }
24  end
25
26  def to_sexpression(tree)
27    return "()" if tree.nil?
28    "(#{tree.value}#{to_sexpression(tree.left)},#{to_sexpression(tree.right)})"
29  end
30
31  def to_s
32    to_sexpression(self)
33  end
34
35  def self.build_from(hash)
36    return nil if hash.nil?
37    Tree.new(hash[:value], left: build_from(hash[:left]), right: build_from(hash[:right]))
38  end
39end