返回顶部

收藏

inorder / preorder / postorder

更多
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)
    list = []
    if @data == nil
      @data = x
    elsif @left == nil
      @left = Tree.new(x)
    elsif @right == nil
      @right = Tree.new(x)
    else
      list << @left
      list << @right
      loop do
        node = list.shift
        if node.left == nil
          node.insert(x)
          break
        else
          list << node.left
        end
        if node.right == nil
          node.insert(x)
          break
        else
          list << node.right
        end
      end
    end
  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

  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 preorder()
    yield @data
    @left.preorder {|y| yield y} if @left != nil
    @right.preorder {|y| yield y} if @right != nil
  end

  def postorder()
    @left.postorder {|y| yield y} if @left != nil
    @right.postorder {|y| yield y} if @right != nil
    yield @data
  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'
tree.preorder {|x| print x, ' '}
print '\n'
tree.postorder {|x| print x, ' '}
print '\n'

标签:Ruby,集合

收藏

0人收藏

支持

0

反对

0

»更多 您可能感兴趣的代码
  1. 2015-12-06 21:03:01Set length, size and empty? by LeoSun
  2. 2016-08-28 09:17:16Implementing Enumerable - Write One Method, Get 22 Free by digua
  3. 2016-08-28 12:59:01Divide a set by its element's class by 胡晋
  4. 2016-02-04 11:37:45Collect in place by 永明
  5. 2016-04-24 14:08:00Map elements in a set by digua
  6. 2016-08-28 09:29:05Sort on two arrays by jeffsui
  7. 2016-08-28 13:17:44Convert a hash to set and divide by zetaliang
  8. 2016-09-20 09:21:04Divide a set by absolute value by 好好学习啊
  9. 2016-04-24 14:16:11Create Your stack by Loli控
  10. 2016-08-28 09:48:44extend Forwardable by 好好学习啊
  11. 2016-08-28 13:39:21Add set operation to Array by 永明

发表评论