human
Convert a Binary Tree to Threaded binary tree | Set 2 ( Efficient ) | Converts tree with given root to threaded binary tree . This function returns rightmost child of root ..
Base cases : Tree is empty or has single node.
Find predecessor if it exists.
Find predecessor of root ( Rightmost child in left subtree ).
Link a thread from predecessor to root ..
If current node is rightmost child.
Recur for right subtree ..
A utility function to find leftmost node in a binary tree rooted with ' root ' . This function is used in inOrder ( ).
Function to do inorder traversal of a threaded binary tree.
Find the leftmost node in Binary Tree.
If this Node is a thread Node , then go to inorder successor.
Else go to the leftmost child in right subtree.
A utility function to create a new node.
Driver Code.
1 / \ 2 3 / \ / \ 4 5 6 7"
Solution in Python:
assistant
#Here is code to convert a Binary Tree to Threaded binary tree and the other steps required.
 def createThreaded ( root ) :
	if root == None :
		return None
	if root . left == None and root . right == None :
		return root
	if root . left != None :
		l = createThreaded ( root . left )
		l . right = root
		l . isThreaded = True
	if root . right == None :
		return root
	return createThreaded ( root . right )
def leftMost ( root ) :
	while root != None and root . left != None :
		root = root . left
	return root
def inOrder ( root ) :
	if root == None :
		return
	cur = leftMost ( root )
	while cur != None :
		print ( cur . key , end = " ▁ " )
		if cur . isThreaded :
			cur = cur . right
		else :
			cur = leftMost ( cur . right )
class newNode :
	def __init__ ( self , key ) :
		self . left = self . right = None
		self . key = key
		self . isThreaded = None
if __name__ == ' _ _ main _ _ ' :
	root = newNode ( 1 )
	root . left = newNode ( 2 )
	root . right = newNode ( 3 )
	root . left . left = newNode ( 4 )
	root . left . right = newNode ( 5 )
	root . right . left = newNode ( 6 )
	root . right . right = newNode ( 7 )
	createThreaded ( root )
	print ( " Inorder ▁ traversal ▁ of ▁ created " , " threaded ▁ tree ▁ is " )
	inOrder ( root )