Skip to main content

Print all paths from root to leaf using recursion in ruby

All path from root to leaf nodes in binary tree

Ruby program for Print all paths from root to leaf using recursion. Here mentioned other language solution.

#  Ruby program for 
#  Efficiently print all paths in 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

	#  Print all the paths from root to leaf in binary tree
	def printPath(node, path) 
		if (node == nil) 
			return
		elsif(node.left == nil && node.right == nil) 
			#  Display path
			print(path ," ", node.data, "\n")
		else
			#  Visit left subtree
			self.printPath(node.left, path + " " + node.data.to_s)
			#  Visit left subtree
			self.printPath(node.right, path + " " + node.data.to_s)
		end
	end
end

def main() 
	tree = BinaryTree.new()
	#        1
	#       / \ 
	#      /   \
	#     5     7
	#    / \   / \
	#   2   4 9   3  
	#      /       \
	#     6         8
	# -------------------
	#    Binary Tree
	tree.root = TreeNode.new(1)
	tree.root.left = TreeNode.new(5)
	tree.root.left.right = TreeNode.new(4)
	tree.root.left.left = TreeNode.new(2)
	tree.root.left.right.left = TreeNode.new(6)
	tree.root.right = TreeNode.new(7)
	tree.root.right.left = TreeNode.new(9)
	tree.root.right.right = TreeNode.new(3)
	tree.root.right.right.right = TreeNode.new(8)
	#  Test
	tree.printPath(tree.root, "")
end

main()

Output

 1 5 2
 1 5 4 6
 1 7 9
 1 7 3 8




Comment

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