All problems
0980MediumDynamic ProgrammingBacktrackingTreeBinary Search TreeBinary Tree

Every Search Tree Over the First n Labels

Tracked in this browser only
Write code

Trains the technique from

LeetCode 95Unique Binary Search Trees II

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

A search tree over the labels 1 through n holds each label once, and every label is larger than everything in its first slot's subtree and smaller than everything in its second slot's subtree.

Read a tree by visiting its top label, then everything in its first slot, then everything in its second slot, which gives one sequence of labels per tree and tells the trees apart.

Return the readings of all the distinct search trees over those labels, listed in increasing dictionary order.

Examples

Example 1

Input
n = 2
Output
[[1, 2], [2, 1]]

Either label may sit at the top. With the smaller on top the larger hangs in its second slot, and the other way round the smaller hangs in the first slot.

Example 2

Input
n = 4
Output
[[1, 2, 3, 4], [1, 2, 4, 3], [1, 3, 2, 4], [1, 4, 2, 3], [1, 4, 3, 2], [2, 1, 3, 4], [2, 1, 4, 3], [3, 1, 2, 4], [3, 2, 1, 4], [4, 1, 2, 3], [4, 1, 3, 2], [4, 2, 1, 3], [4, 3, 1, 2], [4, 3, 2, 1]]

Fourteen search trees hold four labels, and their top-first readings sorted give this list.

Example 3

Input
n = 5
Output
[[1, 2, 3, 4, 5], [1, 2, 3, 5, 4], [1, 2, 4, 3, 5], [1, 2, 5, 3, 4], [1, 2, 5, 4, 3], [1, 3, 2, 4, 5], [1, 3, 2, 5, 4], [1, 4, 2, 3, 5], [1, 4, 3, 2, 5], [1, 5, 2, 3, 4], [1, 5, 2, 4, 3], [1, 5, 3, 2, 4], [1, 5, 4, 2, 3], [1, 5, 4, 3, 2], [2, 1, 3, 4, 5], [2, 1, 3, 5, 4], [2, 1, 4, 3, 5], [2, 1, 5, 3, 4], [2, 1, 5, 4, 3], [3, 1, 2, 4, 5], [3, 1, 2, 5, 4], [3, 2, 1, 4, 5], [3, 2, 1, 5, 4], [4, 1, 2, 3, 5], [4, 1, 3, 2, 5], [4, 2, 1, 3, 5], [4, 3, 1, 2, 5], [4, 3, 2, 1, 5], [5, 1, 2, 3, 4], [5, 1, 2, 4, 3], [5, 1, 3, 2, 4], [5, 1, 4, 2, 3], [5, 1, 4, 3, 2], [5, 2, 1, 3, 4], [5, 2, 1, 4, 3], [5, 3, 1, 2, 4], [5, 3, 2, 1, 4], [5, 4, 1, 2, 3], [5, 4, 1, 3, 2], [5, 4, 2, 1, 3], [5, 4, 3, 1, 2], [5, 4, 3, 2, 1]]

Forty-two search trees hold five labels.

Constraints

  • 1 <= n <= 8

The signature

The editor is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

Python
def generate_trees(n: int) -> list[list[int]]:
Java
public List<List<Integer>> generateTrees(int n)
September 7
Apply