Posted on by Kalkicode
Code Binary Tree

Bottom right view of binary tree in python

Python program for Bottom right view of binary tree. Here more information.

#  Python 3 program for
#  Print bottom-right view of a binary tree

#  Binary Tree Node
class TreeNode :
	def __init__(self, data) :
		#  Set node value
		self.data = data
		self.left = None
		self.right = None
	

class BinaryTree :
	def __init__(self) :
		self.root = None
	
	#  Find bottom right elements
	def bottomRightView(self, node, distance, record) :
		if (node != None) :
			#  Add node of specific distance.
			#  This is adding a new element or
			#  update existing value
			record[distance] = node.data
			#  Visit left subtree And
			#  Here increase the distance by 1
			self.bottomRightView(node.left, distance + 1, record)
			#  Visit to right subtree
			self.bottomRightView(node.right, distance, record)
		
	
	def printBottomRight(self) :
		#  This is store result
		record = dict()
		self.bottomRightView(self.root, 0, record)
		distance = 0
		while (distance < len(record)) :
			#  Display bottom right element
			print("", record.get(distance), end = " ")
			distance += 1
		
	

def main() :
	#  Create new tree
	tree = BinaryTree()
	#  Binary Tree
	#  -----------------------
	#      10
	#     /  \
	#    2    4
	#   /    / \
	#  3    6   5
	#        \
	#         7
	#       /  \
	#      8    11
	#            [⤣⤣⤣⤣]
	#            View position
	#  Add node
	tree.root = TreeNode(10)
	tree.root.left = TreeNode(2)
	tree.root.left.left = TreeNode(3)
	tree.root.right = TreeNode(4)
	tree.root.right.right = TreeNode(5)
	tree.root.right.left = TreeNode(6)
	tree.root.right.left.right = TreeNode(7)
	tree.root.right.left.right.left = TreeNode(8)
	tree.root.right.left.right.right = TreeNode(11)
	#  Test
	tree.printBottomRight()

if __name__ == "__main__": main()

Output

 5  11  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