使用ruby实现树和其他数据结构

ami*_*mir 7 ruby

我是新的Ruby程序员.当我在C++中时,我可以使用指针实现数据结构,但现在在Ruby中,我不知道如何实现这些数据结构(例如树).有人可以帮助我(例如向我介绍一个很好的参考或做一个很好的例子).特别感谢.

Cas*_*per 10

Ruby没有也不需要指针,因为大多数东西都是通过引用传递的.

> a = "hello"
> b = a
> a.object_id == b.object_id
=> true 
Run Code Online (Sandbox Code Playgroud)

在最简单的形式中,树节点可以只是一个结构,具有父节点和左右兄弟节点:

> Node = Struct.new(:parent, :left, :right)
> root = Node.new
> n1   = Node.new(root, "hello", "world")
> root.left = n1
...

> root.left.left
=> "hello"
> root.left.right
=> "world"
Run Code Online (Sandbox Code Playgroud)

有关更完整的实现,您可以查看以下示例:

RubyTree:http: //rubytree.rubyforge.org/rdoc/

SimpleTree:https:
//github.com/ealdent/simple-tree/blob/master/lib/simple_tree.rb