Created
April 13, 2010 08:40
-
-
Save epitron/364431 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Node(1) | |
Node(2) | |
Node(3) | |
Node(4) | |
Node(5) | |
Node(6) | |
Node(7) | |
Node(8) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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