Insertion in binary search tree using recursion in ruby

Ruby program for Insertion in binary search tree using recursion. Here more information.

#  Ruby program for
#  Insertion in binary search tree by using recursion
class TreeNode 
	# Define the accessor and reader of class TreeNode
	attr_reader :data, :left, :right
	attr_accessor :data, :left, :right
	def initialize(data) 
		self.data = data
		self.left = nil
		self.right = nil
	end
end

class BinarySearchTree 
	# Define the accessor and reader of class BinarySearchTree
	attr_reader :root
	attr_accessor :root
	def initialize() 
		self.root = nil
	end

	#  Insert a node element
	def addNode(node, data) 
		if (node != nil) 
			if (node.data >= data) 
				#  When new element is smaller or
				#  equal to current node
				node.left = self.addNode(node.left, data)
			else
				#  When new element is higher to current node
				node.right = self.addNode(node.right, data)
			end

			#  important to manage root node
			return node
		else
			return TreeNode.new(data)
		end
	end

	#  Display preorder
	def preorder(node) 
		if (node != nil) 
			#  Display node value
			print("  ", node.data)
			#  Visit to left subtree
			self.preorder(node.left)
			#  Visit to right subtree
			self.preorder(node.right)
		end
	end

	def inorder(node) 
		if (node != nil) 
			#  Visit to left subtree
			self.inorder(node.left)
			#  Display node value
			print("  ", node.data)
			#  Visit to right subtree
			self.inorder(node.right)
		end
	end

	def postorder(node) 
		if (node != nil) 
			#  Visit to left subtree
			self.postorder(node.left)
			#  Visit to right subtree
			self.postorder(node.right)
			#  Display node value
			print("  ", node.data)
		end
	end
end

def main() 
	tree = BinarySearchTree.new()
	#         10
	#        / \
	#       /   \
	#      4     15
	#     / \   /
	#    3   5 12
	#    -------------
	#    Build binary search tree
	tree.root = tree.addNode(tree.root, 10)
	tree.addNode(tree.root, 4)
	tree.addNode(tree.root, 3)
	tree.addNode(tree.root, 5)
	tree.addNode(tree.root, 15)
	tree.addNode(tree.root, 12)
	#  Display tree nodes
	print("Preorder \n")
	tree.preorder(tree.root)
	print("\nInorder \n")
	tree.inorder(tree.root)
	print("\nPostorder \n")
	tree.postorder(tree.root)
end

main()

Output

Preorder 
  10  4  3  5  15  12
Inorder 
  3  4  5  10  12  15
Postorder 
  3  5  4  12  15  10


Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment







© 2021, kalkicode.com, All rights reserved