#!/usr/bin/env ruby
class Tree
attr_accessor :value, :left, :right
def initialize(value, *leftRight)
@value = value
if 0 < leftRight.length()
@left = leftRight[0]
@right = leftRight[1]
end
end
def preorder()
yield @value
if @left
@left.preorder {|v| yield v }
end
if @right
@right.preorder {|v| yield v }
end
end
end
$my_tree = Tree.new(4,
Tree.new(1, Tree.new(7), Tree.new(3)),
Tree.new(5, Tree.new(6), Tree.new(2)))
def print_preorder(tree)
puts 'preorder:'
tree.preorder {|y| puts y.to_s + "\n" }
end
print_preorder($my_tree)
print_max($my_tree)
should cause the following output to be printed:
max:
7