← DiffPush

Construct BST from Preorder Traversal

Standard Bar Binary Search Trees · Practice Problems O(n) · O(h)

Rebuilding the Route Hierarchy from the Departure Log

A courier network's dispatcher kept only one log: every hub recorded the moment it was opened, before any of its branches. Because each hub's opening value also fixed the boundary its branches could not cross, the whole hierarchy can be rebuilt by replaying the log with running limits — a value beyond the current hub's ceiling belongs to some earlier hub's right wing instead.

Input: An integer array preorder — the preorder traversal (root, left subtree, right subtree) of a binary search tree with unique values.

Output: Return the constructed BST serialized as a level-order array with trailing nulls trimmed.

Constraints

Examples

Example 1

Input: {"preorder":[8,5,1,7,10,12]}
Output: [8,5,10,1,7,null,12]
8 roots the tree; 1 and 7 hang under 5, and 10 gains the right child 12.

Example 2

Input: {"preorder":[2,1,3]}
Output: [2,1,3]
1 is below 2 and 3 is above it, giving a perfectly balanced root.

Solve this in your browser →

Also on LeetCode ↗