Created
July 31, 2019 17:01
-
-
Save manojnaidu619/952ad85d481228a766e7325a1bcbe7e8 to your computer and use it in GitHub Desktop.
Binary Search Tree Implementation in Ruby
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Tree | |
attr_accessor :data, :left, :right | |
def initialize(data) | |
@data = data | |
end | |
end | |
def insert(root, data) | |
if data > root.data | |
if !root.right | |
root.right = Tree.new(data) | |
else | |
insert(root.right, data) | |
end | |
end | |
if data < root.data | |
if !root.left | |
root.left = Tree.new(data) | |
else | |
insert(root.left, data) | |
end | |
end | |
end | |
def ptraverse(root) | |
return if !root | |
print "#{root.data} " # To print values in a single line | |
ptraverse(root.left) if root.left | |
ptraverse(root.right) if root.right | |
end | |
def itraverse(root) | |
return if !root | |
itraverse(root.left) if root.left | |
print "#{root.data} " # To print values in a single line | |
itraverse(root.right) if root.right | |
end | |
def potraverse(root) | |
return if !root | |
potraverse(root.left) if root.left | |
potraverse(root.right) if root.right | |
print "#{root.data} " # To print values in a single line | |
end | |
root = Tree.new(5) | |
[1,3,15,12,19].each {|i| insert(root,i)} | |
itraverse(root) | |
puts "\n" | |
ptraverse(root) | |
puts "\n" | |
potraverse(root) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment