Walk Down a Binary Tree

My goal was to make a generator that could be added to a binary tree class and that had the following characteristics:

Three versions follow. The first two (walk1 and walk2 are partial solutions; the third (walk3) is the best complete solution that I have found so far.

Some basic `BinaryTree code:

class BinaryTree
  attr_reader :value, :right
  
  # Creates a binary tree from an array [value, left_child, right_child],
  # where 'left_child' and 'right_child' may themselves be values.
  def initialize(array)
    if array.class == Array
      @value = array[0]
      @left = BinaryTree.new array[1] if array[1] != nil
      @right = BinaryTree.new array[2] if array[2] != nil
    else
      @value = array # In this case, 'array' isn't really an array
    end      
  end
  
  # Returns true iff this BinaryTree has no children.
  def leaf?
    @left == nil and @right == nil
  end
  
  # Returns the array representation of this binary tree.
  def to_s
    if leaf?
      "#@value"
    else
      "[#@value, #{@left}, #{@right}]"
    end
  end

end

#            a
#           / \
#          b   c
#         / \   \
#        d   e   f
#               /
#              g
bt = BinaryTree.new [:a, [:b, :d, :e], [:c, nil, [:f, :g, nil]]]
puts bt.to_s

A helper method


ask = lambda do |question|
  print question + "  "
  gets[0].chr.upcase
end

$stdout.sync = true # Auto-flush for interactive I/O

First version (walk1)


class BinaryTree
  def walk1(ask) # Pass in 'ask' method as proc
    puts "walk1 is at #@value"
    move = ask.call("  Left or right?") if !leaf?
    if move == 'L' then @left.walk1(ask)
    elsif move == 'R' then @right.walk1(ask)
    end
  end
end

puts
puts "Ready to try walk1..."
bt.walk1(ask)
puts "Finished with walk1."

Second version (walk2)


class BinaryTree
  def walk2(action) # Pass in 'action' method as proc
    action.call(@value)
    return if  leaf?
    print "  Left or right?  " if !leaf?
    move = gets[0].chr.upcase
    if move == 'L'
      @left.walk2(action)
    elsif move == 'R'
      @right.walk2(action)
    else return
    end
  end
end

puts
puts "Ready to try walk2..."
bt.walk2(lambda { |value| puts "walk2 is at #{value}" } )
puts "Finished with walk2."

Third and "final" version (walk3)


class BinaryTree
  def walk3(ask, &block) # Pass in 'ask' method as proc, body as block
    yield @value
    move = ask.call("  Left or right?") if !leaf?
    if move == 'L' then @left.walk3(ask, &block)
    elsif move == 'R' then @right.walk3(ask, &block)
    else yield nil
    end
    rescue NoMethodError
      yield nil
  end
end

puts
puts "Ready to try walk3..."
bt.walk3(ask) { |value| puts "walk3 is at #{value}" if value != nil}
puts "Finished with walk3."

Actually, this could easily be improved. The walk3 method assumes a too specific ask method. A more general approach would be to

  1. provide the current node as a parameter to the ask method, and
  2. expect ask to return one of three values, for example :left, :right, or :done.