[Expected Approach - 1] Using Inorder and Preorder - O(nlogn) Time and O(n) Space
The idea is to find Inorder by sorting the input preorder traversal, then traverse the tree in preorder fashion (using both inorder and preorder traversals) and while traversing store the leaf nodes.
How to traverse in preorder fashion using two arrays representing inorder and preorder traversals?
We iterate the preorder array and for each element find that element in the inorder array. For searching, we can use binary search, since inorder traversal of the binary search tree is always sorted. Now, for each element of preorder array, in binary search, we set the range [l, r].
And when l == r, the leaf node is found. So, initially, l = 0 and l = n - 1 for first element (i.e root) of preorder array. Now, to search for the element on the left subtree of the root, set l = 0 and r= index of root - 1. Also, for all element of right subtree set l = index of root + 1 and r = n -1. Recursively, follow this, until l == r.
[Expected Approach - 2] Using Stack - O(n) Time and O(n) Space
The idea is to use the property of the Binary Search Tree and stack. Traverse the array using two pointer i and j to the array, initially i = 0 and j = 1. Whenever a[i] > a[j], we can say a[j] is left part of a[i], since preorder traversal follows Node -> Left -> Right. So, we push a[i] into the stack.
For those points violating the rule, we start to pop element from the stack till a[i] > top element of the stack and break when it doesn't and print the corresponding jth value.
How does this algorithm work? Preorder traversal traverse in the order: Node, Left, Right. And we know the left node of any node in BST is always less than the node. So preorder traversal will first traverse from root to leftmost node. Therefore, preorder will be in decreasing order first. Now, after decreasing order, there may be a node that is greater or which breaks the decreasing order. So, there can be a case like this :
In case 1, 20 is a leaf node whereas in case 2, 20 is not the leaf node. So, our problem is how to identify if we have to print 20 as a leaf node or not? This is solved using stack. While running above algorithm on case 1 and case 2, when i = 2 and j = 3, state of a stack will be the same in both the case:
So, node 65 will pop 20 and 50 from the stack. This is because 65 is the right child of a node which is before 20. This information we store using the found variable. So, 20 is a leaf node. While in case 2, 40 will not able to pop any element from the stack. Because 40 is the right node of a node which is after 20. So, 20 is not a leaf node. Note: In the algorithm, we will not be able to check the condition of the leaf node of the rightmost node or rightmost element of the preorder. So, simply print the rightmost node because we know this will always be a leaf node in preorder traversal.