27. Print Leaf Nodes from Preorder Traversal of BST
The problem can be found at the following link: ๐ Question Link
๐งฉ Problem Description
Given the preorder traversal of a Binary Search Tree (BST), print all the leaf nodes of this BST without actually reconstructing the tree.
โNote:
It is guaranteed that the input preorder is of a valid BST.
The output order must follow the order of the leaf nodes as they appear during preorder traversal.
๐ Examples
Example 1:
Input:
preorder = [5, 2, 10]
Output:
[2, 10]
Explanation: The BST is:
5 / \ 2 10
Leaf nodes are 2
and 10
.
Example 2:
Input:
preorder = [4, 2, 1, 3, 6, 5]
Output:
[1, 3, 5]
Explanation: The BST is:
4 / \ 2 6 / \ / 1 3 5
Leaf nodes are 1, 3, 5
.
Example 3:
Input:
preorder = [8, 2, 5, 10, 12]
Output:
[5, 12]
Explanation: The BST is:
8 / \ 2 10 \ \ 5 12
Leaf nodes are 5
and 12
.
๐ Constraints
$
1 โค preorder.size() โค 10^3
$$
1 โค preorder[i] โค 10^3
$
โ
My Approach
Single-Pass Stack Sweep
We can determine leaf nodes directly by observing when a nodeโs value is โpopped overโ by a larger successor in preorder. Maintain a stack of ancestors; whenever the next value exceeds stack-top, the previous node is a leaf.
Algorithm Steps:
Initialize an empty stack
st
and an empty result listleafs
.Iterate index
i
from0
topreorder.size() - 2
:Let
cur = preorder[i]
,nxt = preorder[i+1]
.If
cur > nxt
, pushcur
ontost
.Else (i.e.,
nxt > cur
):While
!st.empty()
andnxt > st.top()
, popst
and mark a flag.If flag was set (we popped at least once), record
cur
as a leaf.
After loop, always append the last element
preorder.back()
as a leaf.Return
leafs
.
๐งฎ Time and Auxiliary Space Complexity
Expected Time Complexity: O(n), as we scan the array once and each element is pushed and popped at most once.
Expected Auxiliary Space Complexity: O(n), as in the worst case (strictly decreasing preorder) all elements go into the stack.
๐ง Code (C++)
class Solution {
public:
vector<int> leafNodes(vector<int>& p) {
stack<int> s;
vector<int> r;
for (int i = 0, j = 1; j < p.size(); i++, j++) {
bool f = 0;
if (p[i] > p[j]) s.push(p[i]);
else while (!s.empty() && p[j] > s.top()) s.pop(), f = 1;
if (f) r.push_back(p[i]);
}
r.push_back(p.back());
return r;
}
};
๐งโ๐ป Code (Java)
class Solution {
public ArrayList<Integer> leafNodes(int[] p) {
Stack<Integer> st = new Stack<>();
ArrayList<Integer> r = new ArrayList<>();
for (int i = 0, j = 1; j < p.length; i++, j++) {
boolean f = false;
if (p[i] > p[j]) st.push(p[i]);
else {
while (!st.isEmpty() && p[j] > st.peek()) {
st.pop();
f = true;
}
}
if (f) r.add(p[i]);
}
r.add(p[p.length-1]);
return r;
}
}
๐ Code (Python)
class Solution:
def leafNodes(self, preorder):
s, r = [], []
for i in range(len(preorder)-1):
f = False
if preorder[i] > preorder[i+1]:
s.append(preorder[i])
else:
while s and preorder[i+1] > s[-1]:
s.pop()
f = True
if f:
r.append(preorder[i])
r.append(preorder[-1])
return r
๐ง Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: ๐ฌ Any Questions?. Letโs make this learning journey more collaborative!
โญ If you find this helpful, please give this repository a star! โญ
๐Visitor Count
Last updated