Inorder traversal of binary tree with recursion in ruby

Ruby program for Inorder traversal of binary tree with recursion. Here problem description and explanation.

#  Ruby Program for
#  inorder tree traversal of a Binary Tree
#  using recursion

#  Binary Tree Node
class TreeNode 
	# Define the accessor and reader of class TreeNode
	attr_reader :data, :left, :right
	attr_accessor :data, :left, :right
	def initialize(data) 
		#  Set node value
		self.data = data
		self.left = nil
		self.right = nil
	end

end

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

	#  Display Inorder view of binary tree
	def inorder(node) 
		if (node != nil) 
			#  Visit left subtree
			self.inorder(node.left)
			# Print node value
			print("  ", node.data)
			#  Visit right subtree
			self.inorder(node.right)
		end

	end

end

def main() 
	#  Create new tree
	tree = BinaryTree.new()
	#    Make A Binary Tree
	#    ----------------
	#        15
	#       /  \
	#      24   54
	#     /    /  \
	#    35   62   13
	#  Add tree TreeNode
	tree.root = TreeNode.new(15)
	tree.root.left = TreeNode.new(24)
	tree.root.right = TreeNode.new(54)
	tree.root.right.right = TreeNode.new(13)
	tree.root.right.left = TreeNode.new(62)
	tree.root.left.left = TreeNode.new(35)
	#  Display Tree Node
	tree.inorder(tree.root)
end

main()

Output

  35  24  15  62  54  13


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