class DataStructures::TreeNode
Implements a Tree data structure. TreeNode
represents a single node, and has methods for accessing parents, siblings and children.
Attributes
children[RW]
data[RW]
parent[RW]
Public Class Methods
new(data,parent=nil)
click to toggle source
new TreeNode
object. :data
is the content of the node, can be any Ruby object :parent
optionally specify the parent node. Must be a TreeNode
. Not specifying a parent makes this a root node.
# File lib/datastructures/tree_node.rb, line 13 def initialize(data,parent=nil) @data = data @parent = nil raise "parent must be a TreeNode" unless @parent.nil? || @parent.class == TreeNode self.clear end
Public Instance Methods
add_child(child)
click to toggle source
add a child node.
:child
the node to add as a child. must be a TreeNode
# File lib/datastructures/tree_node.rb, line 22 def add_child child child.parent = self @children << child end
Also aliased as: <<
child_count()
click to toggle source
count the direct children of this node
# File lib/datastructures/tree_node.rb, line 36 def child_count @children.size end
clear()
click to toggle source
remove all children
# File lib/datastructures/tree_node.rb, line 67 def clear @children = Array.new end
descendents()
click to toggle source
return an array of all descendents
# File lib/datastructures/tree_node.rb, line 62 def descendents @children.map { |child| [child, child.descendents] }.flatten end
is_leaf?()
click to toggle source
true if the node is a leaf, i.e. has no children
# File lib/datastructures/tree_node.rb, line 41 def is_leaf? @children.empty? end
Also aliased as: empty?
is_root?()
click to toggle source
true if this node is root, i.e. has no parent
# File lib/datastructures/tree_node.rb, line 48 def is_root? @parent.nil? end
remove_child!(child)
click to toggle source
remove a child node.
:child
the child node to remove. must be a TreeNode
# File lib/datastructures/tree_node.rb, line 29 def remove_child! child @children.delete child end
siblings()
click to toggle source
return an array of the siblings of this node. Nil if root.
# File lib/datastructures/tree_node.rb, line 53 def siblings if self.is_root? nil else @parent.children.reject { |sibling| sibling.equal? self } end end