我正在编写一个 Ruby 脚本并想使用 n 叉树数据结构。
是否有源代码形式的良好实现?谢谢。
最佳答案
为了扩展 Otto 的答案,获取哈希以自动激活数组的一种简单方法是将默认值 block 与 Hash::new
一起使用,如下所示:
node_children = Hash.new { |_node_children, node_key| _node_children[node_key] = [] }
但实际上,代码取决于您要对数组执行的操作。你也可以 用散列和数组设置它们,或者创建一些类:
class Node
attr_accessor :value, :children
def initialize(value, children=[])
@value = value
@children = children
end
def to_s(indent=0)
value_s = @value.to_s
sub_indent = indent + value_s.length
value_s + @children.map { |child| " - " + child.to_s(sub_indent + 3) }.join("\n" + ' ' * sub_indent)
end
end
ROOT = Node.new('root', %w{ farleft left center right farright }.map { |str| Node.new(str) } )
puts "Original Tree"
puts ROOT
puts
ROOT.children.each do |node|
node.children = %w{ one two three four }.map { |str| Node.new(node.value + ':' + str) }
end
puts "New Tree"
puts ROOT
puts
例如,这段代码给出:
Original Tree
root - farleft
- left
- center
- right
- farright
New Tree
root - farleft - farleft:one
- farleft:two
- farleft:three
- farleft:four
- left - left:one
- left:two
- left:three
- left:four
- center - center:one
- center:two
- center:three
- center:four
- right - right:one
- right:two
- right:three
- right:four
- farright - farright:one
- farright:two
- farright:three
- farright:four
关于ruby - "Ruby"做n叉树的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/501232/