Class: TreeLab::Node

Inherits:
Object
  • Object
show all
Defined in:
lib/treelab.rb

Overview

Node class used to represent each node in a binary tree

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(value) ⇒ Node

Returns a new instance of Node.



178
179
180
# File 'lib/treelab.rb', line 178

def initialize(value)
    @value = value
end

Instance Attribute Details

#circleObject

attribute that represents the node in a binary tree canvas



176
177
178
# File 'lib/treelab.rb', line 176

def circle
  @circle
end

#leftObject (readonly)

left child of node



170
171
172
# File 'lib/treelab.rb', line 170

def left
  @left
end

#rightObject (readonly)

right child of node



172
173
174
# File 'lib/treelab.rb', line 172

def right
  @right
end

#valueObject

value of node



174
175
176
# File 'lib/treelab.rb', line 174

def value
  @value
end

Instance Method Details

#delLeftObject

deletes the left child node



207
208
209
210
211
212
# File 'lib/treelab.rb', line 207

def delLeft
    @left = nil
    if(TreeLab::tree) 
        view_tree(TreeLab::tree)
    end
end

#delRightObject

deletes the left child node



215
216
217
218
219
220
# File 'lib/treelab.rb', line 215

def delRight
    @right = nil
    if(TreeLab::tree) 
        view_tree(TreeLab::tree)
    end
end

#inspectObject

return a string representation of the node



228
229
230
# File 'lib/treelab.rb', line 228

def inspect
    return to_s
end

#isLeaf?Boolean

checks whether this node is a leaf node

Returns:

  • (Boolean)


223
224
225
# File 'lib/treelab.rb', line 223

def isLeaf?
    return (left == nil && right == nil);
end

#setLeft(node) ⇒ Object

sets the left child node



183
184
185
186
187
188
189
190
191
192
# File 'lib/treelab.rb', line 183

def setLeft(node)
    raise "Value must be a Node!" if node.class != TreeLab::Node
    raise "cannot attach node to itself" if node == self
    raise "left child is not empty" if @left != nil
    @left = node
    if(TreeLab::tree) 
        view_tree(TreeLab::tree)
    end
    return to_s
end

#setRight(node) ⇒ Object

sets the right child node



195
196
197
198
199
200
201
202
203
204
# File 'lib/treelab.rb', line 195

def setRight(node)
    raise "Value must be a Node!" if node.class != TreeLab::Node
    raise "cannot attach node to itself" if node == self
    raise "left child is not empty" if @right != nil
    @right = node
    if(TreeLab::tree) 
        view_tree(TreeLab::tree)
    end
    return to_s
end

#to_sObject

returns a string representation of the node



233
234
235
236
237
238
239
240
241
242
243
244
245
246
# File 'lib/treelab.rb', line 233

def to_s    
    s = "Value: "+value.to_s;
    if (left != nil)
        s += ", left child: "+left.value.to_s;
    else
        s += ", left child: nil"
    end
    if (right != nil)
        s += ", right child: "+right.value.to_s;
    else
        s += ", right child: nil"
    end
    return s;
end