Skip to main content

Detect next node at same level of a key in binary tree in python

Next node of same level of tree

Python program for Detect next node at same level of a key in binary tree. Here mentioned other language solution.

#  Python 3 program for
#  Find the next node of the key at the same 
#  level in the 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
		self.status = -1
		self.result = None
	
	#  Method which are find next node of same level
	def findNextNode(self, temp, level, node) :
		if (temp != None) :
			if (self.status == -1 and temp.data == node) :
				#  When found node value
				self.status = level
			elif (self.status == level and self.result == None) :
				#  Next node of same level
				self.result = temp
			
			#  Visit to left subtree
			self.findNextNode(temp.left, level + 1, node)
			#  Visit to right subtree
			self.findNextNode(temp.right, level + 1, node)
		
	
	#  This are handling the request of to finding next
	#  node in same level by given node
	def nextNode(self, node) :
		#  Reset the result indicator
		self.status = -1
		self.result = None
		#  Find next node
		self.findNextNode(self.root, 0, node)
		print("\n Node : ", node)
		print(" Result : ", end = "")
		#  Test Case
		if (self.status == -1) :
			#  Case A
			#  When node values are not exist
			print("Not found")
		elif (self.result == None) :
			#  Case B
			#  When next node is not found
			print("None")
		else :
			#  Case C
			#  When next node are exist
			print(self.result.data)
		
	

def main() :
	#  Create new tree
	tree = BinaryTree()
	#   Make A Binary Tree
	#  ---------------------
	#        1
	#       / \ 
	#      /   \ 
	#     /     \
	#    2       4
	#   /       / \
	#  /       /   \
	#  3      6     5
	#   \      \   /
	#    7      8 11
	#  Add node in Binary Tree
	tree.root = TreeNode(1)
	tree.root.left = TreeNode(2)
	tree.root.left.left = TreeNode(3)
	tree.root.left.left.right = TreeNode(7)
	tree.root.right = TreeNode(4)
	tree.root.right.right = TreeNode(5)
	tree.root.right.right.left = TreeNode(11)
	tree.root.right.left = TreeNode(6)
	tree.root.right.left.right = TreeNode(8)
	#  Testing
	tree.nextNode(3)
	tree.nextNode(7)
	tree.nextNode(6)
	tree.nextNode(5)
	tree.nextNode(8)
	tree.nextNode(1)

if __name__ == "__main__": main()

Output

 Node :  3
 Result : 6

 Node :  7
 Result : 8

 Node :  6
 Result : 5

 Node :  5
 Result : None

 Node :  8
 Result : 11

 Node :  1
 Result : None




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