Create Your tree : Your tree « Collections « Ruby

Home
Ruby
1.ActiveRecord
2.Array
3.CGI
4.Class
5.Collections
6.Database
7.Date
8.Design Patterns
9.Development
10.File Directory
11.GUI
12.Hash
13.Language Basics
14.Method
15.Network
16.Number
17.Rails
18.Range
19.Reflection
20.Statement
21.String
22.Threads
23.Time
24.Tk
25.Unit Test
26.Windows Platform
27.XML
Ruby » Collections » Your tree 




Create Your tree


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

end


  items = [1234567]

  tree = Tree.new

  items.each {|x| tree.insert(x)}

  tree.traverse {|x| print "#{x} "}
  print "\n"

  # Prints "1 2 3 4 5 6 7 "

 














Related examples in the same category
1.inorder / preorder / postorder
2.search a tree
3.to string
4.to array
5.infix
6.Writing an Iterator Over a Data Structure
7.Loop through a tree
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.