Версия для печати темы
Нажмите сюда для просмотра этой темы в оригинальном формате |
Форум программистов > Ruby: Общие вопросы > Ruby синтаксис |
Автор: moni 23.4.2015, 08:14 |
вывести само дерево в любом виде (напр: (@left, @right) , .... или @data (@left, @right), ...) class Tree attr_accessor :left attr_accessor :right attr_accessor :data def initialize(x=nil) @left = nil @right = nil @data = x end def insert(x) if @data == nil @data = x elsif x <= @data if @left == nil @left = Tree.new x else @left.insert x end else if @right == nil @right = Tree.new x else @right.insert x end end end def inorder() @left.inorder {|y| yield y} if @left != nil yield @data @right.inorder {|y| yield y} if @right != nil end def traverse() list = [] yield @data list << @left if @left != nil list << @right if @right != nil loop do break if list.empty? node = list.shift yield node.data list << node.left if node.left != nil list << node.right if node.right != nil end end end items = [50, 20, 80, 10, 30, 70, 90, 5, 14, 28, 41, 66, 75, 88, 96] tree = Tree.new items.each {|x| tree.insert(x)} tree.inorder {|x| print x, " "} print "\n" |