[ create a new paste ] login | about

Link: http://codepad.org/EFUQzkEv    [ raw code | output | fork ]

joshua_cheek - Ruby, pasted on Feb 26:
# 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


Output:
1
2
3
4
5
6
7
Follow tree from end back to root
by following the path of parents
8
7
5
4
1


Create a new paste based on this one


Comments: