# a simple tree that keeps track of the value of a node
# each node tracks it's parent, but parents do not track their children
# so you can only traverse the tree from end to start
class SimpleTree
attr_accessor :value , :parent
def initialize( value , parent = nil )
self.value , self.parent = value , parent
end
# add a child
def <<( value )
SimpleTree.new value , self
end
end
# note: the <<= operator is just like the += operator
# when you say current <<= 4, that translates to (current = current << 4)
current = SimpleTree.new 1
# currently tree looks like this
# (the star indicates that this node is currently being tracked)
# *1
current << 2
current << 3
current <<= 4
# 1
# /|\
# 2 3 *4
current <<= 5
# 1
# /|\
# 2 3 4
# |
# *5
current << 6
current <<= 7
# 1
# /|\
# 2 3 4
# |
# 5
# / \
# 6 *7
current <<=8
# 1
# /|\
# 2 3 4
# |
# 5
# / \
# 6 7
# |
# *8
puts "Follow tree from end back to root"
puts "by following the path of parents"
while current
puts current.value
current = current.parent
end