Intuition
In a preorder BST stream, each value either becomes the left child of the previous node (if smaller) or the right child of the nearest ancestor it is still larger than. A decreasing stack tracks candidate parents.
Explanation
Stack of ancestors
Keep a stack of nodes with strictly decreasing values. For each new value v:
- If
v < stack.top, it is that node's left child. - Otherwise pop while
stack.top < v; the last popped node is the parent, andvis its right child.
Push v after linking. This builds the BST in one pass.
for v in preorder[1:]:
if v < stack[-1].val: stack[-1].left = node
else: while stack and stack[-1].val < v: parent = stack.pop(); parent.right = node
stack.append(node)
Worked example
[8,5,1,7,10,12] → root 8, left subtree {5,1,7}, right subtree {10,12}.
Complexity
- Time: O(n).
- Space: O(n).
Implementation
import java.util.ArrayDeque;
import java.util.Deque;
class Solution {
public TreeNode bstFromPreorder(int[] preorder) {
if (preorder.length == 0) return null;
TreeNode root = new TreeNode(preorder[0]);
Deque<TreeNode> stack = new ArrayDeque<>();
stack.push(root);
for (int i = 1; i < preorder.length; i++) {
TreeNode node = new TreeNode(preorder[i]);
if (preorder[i] < stack.peek().val) {
stack.peek().left = node;
} else {
TreeNode parent = stack.peek();
while (!stack.isEmpty() && stack.peek().val < preorder[i]) {
parent = stack.pop();
}
parent.right = node;
}
stack.push(node);
}
return root;
}
}