Practice › Trees
Construct a BST from Preorder
Medium · Trees · Asked at Amazon, Microsoft, Meta, Oracle
The array is the preorder traversal of a binary search tree with distinct values. Rebuild the tree and print its postorder traversal (left subtree, right subtree, root).
Input
First line: n. Second line: the n values in preorder.
Output
The postorder traversal, space-separated.
Constraints
- 1 ≤ n ≤ 10^4
- 1 ≤ values ≤ 10^9
- all values distinct
Build recursively with an upper bound: take the next preorder value if it is below the bound, then build its left subtree with bound = that value and its right subtree with the parent’s bound. Each value is read once — O(n).
Example 1
Input
6 8 5 1 7 10 12
Output
1 7 5 12 10 8
Example 2
Input
2 1 3
Output
3 1
Hints
- The first value is the root; the values after it that are smaller form the left subtree.
- Instead of searching for that split, build with an upper bound.
- Consume the next preorder value only if it is below the current bound.
Approach
build(bound): if the next preorder value is missing or ≥ bound, return null. Otherwise create a node with it, then node.left = build(node value) and node.right = build(bound). The very first call uses an infinite bound. Every value is consumed exactly once, so it is O(n). Then print the postorder traversal (an explicit stack avoids deep recursion).
Complexity: O(n) time · O(n) space
Solution
C++ solution
#include <bits/stdc++.h>
using namespace std;
struct Node {
long long val;
Node *left = nullptr, *right = nullptr;
Node(long long v) : val(v) {}
};
vector<long long> pre;
size_t idx = 0;
Node *build(long long bound) {
if (idx == pre.size() || pre[idx] >= bound) return nullptr;
Node *n = new Node(pre[idx++]);
n->left = build(n->val);
n->right = build(bound);
return n;
}
int main() {
int n;
cin >> n;
pre.resize(n);
for (auto &x : pre) cin >> x;
Node *root = build(LLONG_MAX);
vector<pair<Node *, bool>> st = {{root, false}};
string out;
while (!st.empty()) {
auto _b = st.back();
auto node = _b.first;
auto seen = _b.second;
st.pop_back();
if (!node) continue;
if (seen) out += (out.empty() ? "" : " ") + to_string(node->val);
else {
st.push_back({node, true});
st.push_back({node->right, false});
st.push_back({node->left, false});
}
}
cout << out << "\n";
return 0;
}Python solution
import sys
class Node:
__slots__ = ("val", "left", "right")
def __init__(self, val):
self.val, self.left, self.right = val, None, None
sys.setrecursionlimit(20000)
data = list(map(int, sys.stdin.read().split()))
pre = data[1 : 1 + data[0]]
idx = 0
def build(bound):
global idx
if idx == len(pre) or pre[idx] >= bound:
return None
node = Node(pre[idx])
idx += 1
node.left = build(node.val)
node.right = build(bound)
return node
root = build(float("inf"))
out = []
stack = [(root, False)]
while stack:
node, seen = stack.pop()
if node is None:
continue
if seen:
out.append(node.val)
else:
stack.append((node, True))
stack.append((node.right, False))
stack.append((node.left, False))
print(*out)Java solution
import java.io.*;
import java.util.*;
public class Main {
static class Node {
long val;
Node left, right;
Node(long v) { val = v; }
}
static long[] pre;
static int idx = 0;
static Node build(long bound) {
if (idx == pre.length || pre[idx] >= bound) return null;
Node n = new Node(pre[idx++]);
n.left = build(n.val);
n.right = build(bound);
return n;
}
public static void main(String[] args) throws IOException {
StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
in.nextToken();
int n = (int) in.nval;
pre = new long[n];
for (int i = 0; i < n; i++) {
in.nextToken();
pre[i] = (long) in.nval;
}
Node root = build(Long.MAX_VALUE);
ArrayDeque<Object[]> st = new ArrayDeque<>();
st.push(new Object[] {root, false});
StringBuilder sb = new StringBuilder();
while (!st.isEmpty()) {
Object[] t = st.pop();
Node node = (Node) t[0];
if (node == null) continue;
if ((boolean) t[1]) {
if (sb.length() > 0) sb.append(' ');
sb.append(node.val);
} else {
st.push(new Object[] {node, true});
st.push(new Object[] {node.right, false});
st.push(new Object[] {node.left, false});
}
}
System.out.println(sb);
}
}Solve Construct a BST from Preorder online · All practice problems