Computer Science Canada

building trees in Ruby

Author:  Tony [ Fri Sep 02, 2005 5:07 pm ]
Post subject:  building trees in Ruby

how would I go about putting one together and then traversing it?

Author:  wtd [ Fri Sep 02, 2005 6:23 pm ]
Post subject: 

code:
class BTreeNode
   attr_reader :value
   attr_accessor :left, :right

   def initialize(value, left = nil, right = nil)
      @value = value
      @left, @right = left, right
   end

   def to_a
      ...
   end

   def each
      ...
   end
end

Author:  Tony [ Sat Sep 03, 2005 12:40 am ]
Post subject: 

I don't quite get it. How would a pointer look like, and how would I use it?

Other than an array that is Laughing

Author:  wtd [ Sat Sep 03, 2005 12:49 am ]
Post subject: 

No pointers.

But you can have an instance variable be either nil or another BTreeNode.

Author:  Tony [ Sat Sep 03, 2005 1:56 am ]
Post subject: 

I suppose I could always just inline C Laughing

Author:  wtd [ Sat Sep 03, 2005 2:58 am ]
Post subject: 

Ok... let's look at traversing a Ruby binary tree.

code:
def values
   output = [@value]
   output.push(*@left.values) unless @left.nil?
   output.push(*@right.values) unless @right.nil?
   output
end

Author:  Cervantes [ Mon Sep 05, 2005 5:28 pm ]
Post subject: 

Though I haven't finished reading it, perhaps wtd's tutorial on linked lists and binary trees in Haskell, Java, and Ruby will help.

Author:  wtd [ Mon Sep 05, 2005 5:37 pm ]
Post subject: 

The very short answer...

"nil" is your Ruby equivalent to a NULL pointer.

Author:  Tony [ Mon Sep 05, 2005 9:07 pm ]
Post subject: 

ah, excellent Very Happy I'll be trying out the examples.


: