BST is data-structure that is used to store data in a tree or hierarchical format.
In bst we make a root node and store the data which is lower than the value of root node to left part of the root node and the data which is greater than the root node store it on right side of the root node
Code
# creating a node
class Node
attr_accessor :data,:left,:right
def initialize data
@data=data
@left=@right=nil
end
end
# inserting values in tree
def insert root,data
if root==nil
return Node.new(data)
elsif root.data<data
root.right=insert root.right,data
else
root.left=insert root.left,data
end
return root
end
# printing the values in preorder fashion
def preorder root
if root==nil
return
end
print "#{root.data} "
preorder root.left
preorder root.right
end
root=nil
root=insert(root,10)
insert(root,9)
insert(root,12)
preorder root
puts
output:- 10 9 12
here is a bst and we are printing the tree in preorder manner.
Top comments (0)