Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Move from brute-force thinking to an efficient approach using array strategy.
Given an array of integers preorder, which represents the preorder traversal of a BST (i.e., binary search tree), construct the tree and return its root.
It is guaranteed that there is always possible to find a binary search tree with the given requirements for the given test cases.
A binary search tree is a binary tree where for every node, any descendant of Node.left has a value strictly less than Node.val, and any descendant of Node.right has a value strictly greater than Node.val.
A preorder traversal of a binary tree displays the value of the node first, then traverses Node.left, then traverses Node.right.
Example 1:
Input: preorder = [8,5,1,7,10,12] Output: [8,5,10,1,7,null,12]
Example 2:
Input: preorder = [1,3] Output: [1,null,3]
Constraints:
1 <= preorder.length <= 1001 <= preorder[i] <= 1000preorder are unique.Problem summary: Given an array of integers preorder, which represents the preorder traversal of a BST (i.e., binary search tree), construct the tree and return its root. It is guaranteed that there is always possible to find a binary search tree with the given requirements for the given test cases. A binary search tree is a binary tree where for every node, any descendant of Node.left has a value strictly less than Node.val, and any descendant of Node.right has a value strictly greater than Node.val. A preorder traversal of a binary tree displays the value of the node first, then traverses Node.left, then traverses Node.right.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Stack · Tree
[8,5,1,7,10,12]
[1,3]
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #1008: Construct Binary Search Tree from Preorder Traversal
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
private int[] preorder;
public TreeNode bstFromPreorder(int[] preorder) {
this.preorder = preorder;
return dfs(0, preorder.length - 1);
}
private TreeNode dfs(int i, int j) {
if (i > j) {
return null;
}
TreeNode root = new TreeNode(preorder[i]);
int l = i + 1, r = j + 1;
while (l < r) {
int mid = (l + r) >> 1;
if (preorder[mid] > preorder[i]) {
r = mid;
} else {
l = mid + 1;
}
}
root.left = dfs(i + 1, l - 1);
root.right = dfs(l, j);
return root;
}
}
// Accepted solution for LeetCode #1008: Construct Binary Search Tree from Preorder Traversal
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func bstFromPreorder(preorder []int) *TreeNode {
var dfs func(i, j int) *TreeNode
dfs = func(i, j int) *TreeNode {
if i > j {
return nil
}
root := &TreeNode{Val: preorder[i]}
l, r := i+1, j+1
for l < r {
mid := (l + r) >> 1
if preorder[mid] > preorder[i] {
r = mid
} else {
l = mid + 1
}
}
root.Left = dfs(i+1, l-1)
root.Right = dfs(l, j)
return root
}
return dfs(0, len(preorder)-1)
}
# Accepted solution for LeetCode #1008: Construct Binary Search Tree from Preorder Traversal
class Solution:
def bstFromPreorder(self, preorder: List[int]) -> Optional[TreeNode]:
def dfs(i: int, j: int) -> Optional[TreeNode]:
if i > j:
return None
root = TreeNode(preorder[i])
l, r = i + 1, j + 1
while l < r:
mid = (l + r) >> 1
if preorder[mid] > preorder[i]:
r = mid
else:
l = mid + 1
root.left = dfs(i + 1, l - 1)
root.right = dfs(l, j)
return root
return dfs(0, len(preorder) - 1)
// Accepted solution for LeetCode #1008: Construct Binary Search Tree from Preorder Traversal
// Definition for a binary tree node.
// #[derive(Debug, PartialEq, Eq)]
// pub struct TreeNode {
// pub val: i32,
// pub left: Option<Rc<RefCell<TreeNode>>>,
// pub right: Option<Rc<RefCell<TreeNode>>>,
// }
//
// impl TreeNode {
// #[inline]
// pub fn new(val: i32) -> Self {
// TreeNode {
// val,
// left: None,
// right: None
// }
// }
// }
use std::cell::RefCell;
use std::rc::Rc;
impl Solution {
pub fn bst_from_preorder(preorder: Vec<i32>) -> Option<Rc<RefCell<TreeNode>>> {
fn dfs(preorder: &Vec<i32>, i: usize, j: usize) -> Option<Rc<RefCell<TreeNode>>> {
if i > j {
return None;
}
let root = Rc::new(RefCell::new(TreeNode::new(preorder[i])));
let mut l = i + 1;
let mut r = j + 1;
while l < r {
let mid = (l + r) >> 1;
if preorder[mid] > preorder[i] {
r = mid;
} else {
l = mid + 1;
}
}
let mut root_ref = root.borrow_mut();
root_ref.left = dfs(preorder, i + 1, l - 1);
root_ref.right = dfs(preorder, l, j);
Some(root.clone())
}
dfs(&preorder, 0, preorder.len() - 1)
}
}
// Accepted solution for LeetCode #1008: Construct Binary Search Tree from Preorder Traversal
/**
* Definition for a binary tree node.
* class TreeNode {
* val: number
* left: TreeNode | null
* right: TreeNode | null
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
* }
*/
function bstFromPreorder(preorder: number[]): TreeNode | null {
const dfs = (i: number, j: number): TreeNode | null => {
if (i > j) {
return null;
}
const root = new TreeNode(preorder[i]);
let [l, r] = [i + 1, j + 1];
while (l < r) {
const mid = (l + r) >> 1;
if (preorder[mid] > preorder[i]) {
r = mid;
} else {
l = mid + 1;
}
}
root.left = dfs(i + 1, l - 1);
root.right = dfs(l, j);
return root;
};
return dfs(0, preorder.length - 1);
}
Use this to step through a reusable interview workflow for this problem.
For each element, scan left (or right) to find the next greater/smaller element. The inner scan can visit up to n elements per outer iteration, giving O(n²) total comparisons. No extra space needed beyond loop variables.
Each element is pushed onto the stack at most once and popped at most once, giving 2n total operations = O(n). The stack itself holds at most n elements in the worst case. The key insight: amortized O(1) per element despite the inner while-loop.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Pushing without popping stale elements invalidates next-greater/next-smaller logic.
Usually fails on: Indices point to blocked elements and outputs shift.
Fix: Pop while invariant is violated before pushing current element.
Wrong move: Recursive traversal assumes children always exist.
Usually fails on: Leaf nodes throw errors or create wrong depth/path values.
Fix: Handle null/base cases before recursive transitions.