Class: AdderTreeNode

Inherits:
Object show all
Defined in:
lib/javaclass/adder_tree.rb

Overview

A node in the AdderTree.

Author

Peter Kofler

Direct Known Subclasses

AdderTree

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(data, parent) ⇒ AdderTreeNode

Returns a new instance of AdderTreeNode.



8
9
10
11
12
# File 'lib/javaclass/adder_tree.rb', line 8

def initialize(data, parent)
  @data = data
  @parent = parent
  @children = []
end

Instance Attribute Details

#dataObject (readonly)

Returns the value of attribute data.



6
7
8
# File 'lib/javaclass/adder_tree.rb', line 6

def data
  @data
end

#parentObject (readonly)

Returns the value of attribute parent.



5
6
7
# File 'lib/javaclass/adder_tree.rb', line 5

def parent
  @parent
end

Instance Method Details

#add(o) ⇒ Object



18
19
20
21
22
# File 'lib/javaclass/adder_tree.rb', line 18

def add(o)
  node = AdderTreeNode.new(o, self)
  @children << node
  node
end

#childrenObject



14
15
16
# File 'lib/javaclass/adder_tree.rb', line 14

def children
  @children.dup
end

#contain?(o) ⇒ Boolean

Returns:

  • (Boolean)


24
25
26
27
28
29
30
# File 'lib/javaclass/adder_tree.rb', line 24

def contain?(o)
  if @data == o
    self
  else
    @children.find { |child| child.contain?(o) }
  end
end

#debug_printObject

Prints the tree to the console. Each level of the tree is intended by a blank.



64
65
66
67
# File 'lib/javaclass/adder_tree.rb', line 64

def debug_print
  puts ' ' * level + data
  @children.each { |child| child.debug_print }
end

#levelObject



32
33
34
# File 'lib/javaclass/adder_tree.rb', line 32

def level
  @parent.level + 1
end

#levelsObject



45
46
47
# File 'lib/javaclass/adder_tree.rb', line 45

def levels
  ( [1] + @children.map { |child| 1 + child.levels } ).max
end

#rootObject



36
37
38
# File 'lib/javaclass/adder_tree.rb', line 36

def root
  @parent.root
end

#sizeObject

Return the number of nodes this this (sub-)tree.



41
42
43
# File 'lib/javaclass/adder_tree.rb', line 41

def size
  @children.inject(1) { |sum, child| sum + child.size }
end

#to_aObject

Return an array of all children. Each child has its own array. For example

tree = AdderTree.new(0)
tree.add(1)
tree.to_a               # => [0, [1]]


53
54
55
56
57
58
59
60
61
# File 'lib/javaclass/adder_tree.rb', line 53

def to_a
  if @children.size > 0
    sublist = []
    @children.each { |child| child.to_a.each { |c| sublist << c } } 
    [data, sublist]
  else
    [data]
  end
end