Created
July 23, 2012 00:25
-
-
Save ryancurtin/3161463 to your computer and use it in GitHub Desktop.
Treenode problem
This file contains 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 TreeNode | |
attr :children | |
attr_reader :parent | |
def name=(value) | |
@name=value | |
end | |
def name | |
@name | |
end | |
def parents | |
@parents | |
end | |
def parents=(value) | |
@parents=value | |
end | |
def initialize(name=nil) | |
@name = name | |
@children = [] | |
@parents = [] | |
end | |
def add_child(child) | |
@children << child | |
child.parent = self | |
child.parents = self.parents | |
child.add_parent(self) | |
end | |
def add_parent(parent) | |
@parents << parent | |
end | |
def parent_count | |
@parent.count | |
end | |
def children_count | |
@children.count | |
end | |
def parent=(new_parent) | |
@parent = new_parent | |
end | |
def is_child?(tree_node) | |
if tree_node.parent == self | |
true | |
else | |
false | |
end | |
end | |
def show_ancestors | |
self.parents.each do |parent| | |
print "#{parent.name}" | |
print ">" | |
end | |
print self.name | |
end | |
end | |
node_parent = TreeNode.new("parent") | |
node_child = TreeNode.new("child") | |
node_grandchild = TreeNode.new("grandchild") | |
node_parent.add_child(node_child) | |
node_child.add_child(node_grandchild) | |
node_grandchild.show_ancestors |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment