Leaf nodes from Preorder of a Binary Search Tree | Binary Search ; Poto the index in preorder . ; Function to prLeaf Nodes by doing preorder traversal of tree using preorder and inorder arrays . ; If l == r , therefore no right or left subtree . So , it must be leaf Node , print it . ; If array is out of bound , return . ; Finding the index of preorder element in inorder array using binary search . ; Incrementing the index . ; Finding on the left subtree . ; Finding on the right subtree . ; Finds leaf nodes from given preorder traversal . ; To store inorder traversal ; Copy the preorder into another array . ; Finding the inorder by sorting the array . ; Print the Leaf Nodes . ; Driver Code
def binarySearch ( inorder , l , r , d ) : NEW_LINE INDENT mid = ( l + r ) >> 1 NEW_LINE if ( inorder [ mid ] == d ) : NEW_LINE INDENT return mid NEW_LINE DEDENT elif ( inorder [ mid ] > d ) : NEW_LINE INDENT return binarySearch ( inorder , l , mid - 1 , d ) NEW_LINE DEDENT else : NEW_LINE INDENT return binarySearch ( inorder , mid + 1 , r , d ) NEW_LINE DEDENT ind = [ 0 ] NEW_LINE DEDENT def leafNodesRec ( preorder , inorder , l , r , ind , n ) : NEW_LINE INDENT if ( l == r ) : NEW_LINE INDENT print ( inorder [ l ] , end = " ▁ " ) NEW_LINE ind [ 0 ] = ind [ 0 ] + 1 NEW_LINE return NEW_LINE DEDENT if ( l < 0 or l > r or r >= n ) : NEW_LINE INDENT return NEW_LINE DEDENT loc = binarySearch ( inorder , l , r , preorder [ ind [ 0 ] ] ) NEW_LINE ind [ 0 ] = ind [ 0 ] + 1 NEW_LINE leafNodesRec ( preorder , inorder , l , loc - 1 , ind , n ) NEW_LINE leafNodesRec ( preorder , inorder , loc + 1 , r , ind , n ) NEW_LINE DEDENT def leafNodes ( preorder , n ) : NEW_LINE INDENT inorder = [ 0 ] * n NEW_LINE for i in range ( n ) : NEW_LINE INDENT inorder [ i ] = preorder [ i ] NEW_LINE DEDENT inorder . sort ( ) NEW_LINE ind = [ 0 ] NEW_LINE leafNodesRec ( preorder , inorder , 0 , n - 1 , ind , n ) NEW_LINE DEDENT preorder = [ 890 , 325 , 290 , 530 , 965 ] NEW_LINE n = len ( preorder ) NEW_LINE leafNodes ( preorder , n ) NEW_LINE