To identify leaf nodes from a given preorder traversal of a binary search tree (BST), we employ a recursive approach that utilizes the properties of BSTs and preorder traversal. The algorithm maintains two variables,min and max, which define the valid range for each node based on its position in the tree. Starting with an index i set to zero, we traverse the preorder array. For each node, we check if its value lies within the specified range. if so, we consider it a valid node. We then increment the index and make recursive calls to check for potential left and right children, adjusting the min and max values accordingly. If both recursive calls return false, indicating that the node has no children, we store the node’s value as it is a leaf.
Below is the implementation of the above approach:
Output
2 7 13
Time Complexity: O(n), As we are traversing the BST only once. Auxiliary Space: O(h), here h is the height of the BST and the extra space is used in the recursion call stack.