On 2005-07-22 22:05:26 +0900, Ruby Quiz wrote:
[Quiz #40]

Implementation:

class HeapVisualizer
  def initialize(heap)
    @heap = heap.instance_variable_get(:@heap)[1..-1]
  end

  def to_s
    @curved = [ ]
    recurse
  end

  private

  def recurse(node = 0, level = 0)
    result = ''
    return result unless @heap[node]
    for l in 0 ... level
      result << if @curved[l]
        l == level - 1 ? '`---' : ' ' * 4
      else
        l == level - 1 ? '+---' : '|   '
      end
    end
    result << "#{@heap[node]}\n"
    left, right = (node << 1) + 1, (node << 1) + 2
    if @heap[left]
      @curved[level] = @heap[right] ? false : true
      result << recurse(left, level + 1)
      if @heap[right]
        @curved[level] = true
        result << recurse(right, level + 1)
      end
    end
    result
  end
end

Usage:

def to_s(  )
  HeapVisualizer.new(self).to_s
end

Output:

12
+---20
|   +---29
|   |   +---35
|   |   `---40
|   `---23
|       +---26
|       `---51
`---15
    +---17
    |   `---19
    `---22
12
+---20
|   +---29
|   |   +---35
|   |   `---40
|   `---23
|       +---26
|       `---51
`---13
    +---15
    |   +---19
    |   `---17
    `---22
13
+---20
|   +---29
|   |   +---35
|   |   `---40
|   `---23
|       +---26
|       `---51
`---15
    +---17
    |   `---19
    `---22


-- 
Florian Frank