Skip to content

Instantly share code, notes, and snippets.

@epitron
Created April 13, 2010 08:40
Show Gist options
  • Save epitron/364431 to your computer and use it in GitHub Desktop.
Save epitron/364431 to your computer and use it in GitHub Desktop.
Node(1)
Node(2)
Node(3)
Node(4)
Node(5)
Node(6)
Node(7)
Node(8)
class Node
@@counter = 0
attr_reader :parent, :children
def initialize(parent=nil, children=nil)
@parent = parent
@children = children || []
@@counter += 1
@num = @@counter
end
def root?
parent.nil?
end
def parent=(node)
raise "Not a node!" unless node.is_a? Node
@parent = node
node.children << self
end
def <<(node)
raise "Not a node!" unless node.is_a? Node
node.parent = self
end
def inspect
"#<#{name} parent=#{parent.inspect}, children=#{children.inspect}>"
end
def name
"Node(#{@num})"
end
def walk(level=0, &block)
yield [self, level]
children.each do |child|
child.walk(level+1, &block)
end
end
def draw
walk do |node, level|
puts " "*level + node.name
end
end
end
root = Node.new\
<< (
Node.new\
<< Node.new\
<< (
Node.new\
<< Node.new
)
)\
<< Node.new\
<< (
Node.new\
<< Node.new
)
root.draw
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment