Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for Binary search tree in ruby
Sourav das
Sourav das

Posted on

     

Binary search tree in ruby

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 nodeclassNodeattr_accessor:data,:left,:rightdefinitializedata@data=data@left=@right=nilendend# inserting values in treedefinsertroot,dataifroot==nilreturnNode.new(data)elsifroot.data<dataroot.right=insertroot.right,dataelseroot.left=insertroot.left,dataendreturnrootend# printing the values in preorder fashiondefpreorderrootifroot==nilreturnendprint"#{root.data} "preorderroot.leftpreorderroot.rightendroot=nilroot=insert(root,10)insert(root,9)insert(root,12)preorderrootputs
Enter fullscreen modeExit fullscreen mode

output:- 10 9 12
here is a bst and we are printing the tree in preorder manner.

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

I am a computer science student and a full stack coder
  • Location
    kolkata
  • Education
    bhairab ganguly college
  • Joined

More fromSourav das

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp