
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
output:- 10 9 12
here is a bst and we are printing the tree in preorder manner.
Top comments(0)
Subscribe
For further actions, you may consider blocking this person and/orreporting abuse