C++ 0095.cpp
class Solution {
TreeNode* add(TreeNode* root, int value)
{
if (!root)
return new TreeNode(value);
if (value < root->val)
root->left = add(root->left, value);
else
root->right = add(root->right, value);
return root;
}
string flatten(TreeNode* root)
{
if (!root)
return "";
return "L" + flatten(root->left) + "V" + to_string(root->val) + "R" + flatten(root->right);
}
public:
vector<TreeNode*> generateTrees(int n) {
vector<int> nums;
for (int i = 1; i <= n; i++)
nums.push_back(i);
map<string, TreeNode*> trees;
do
{
TreeNode* root = nullptr;
for (auto n : nums)
root = add(root, n);
trees[flatten(root)] = root;
} while (next_permutation(nums.begin(), nums.end()));
vector<TreeNode*> result;
for (auto t : trees)
result.push_back(t.second);
return result;
}
};
Difficulty
and has an acceptance rate of about 63% (900k+ submissions).
Typical patterns to solve this problem:
- Backtracking
- Binary Search Tree
- Binary Tree
- Dynamic Programming
- Tree
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation generates all structurally unique binary search trees (BSTs) that can be built from the integers 1 through n. It does so by enumerating every permutation of the input numbers, inserting the values into a BST in the order dictated by the permutation, and then using a string representation of each tree to eliminate duplicates. The final collection of distinct tree roots is returned as a vector.
Key Steps
Preparing the integer sequence
The algorithm starts by constructing a vector that holds the numbers from 1 to n. This vector serves as the source for permutation generation.
vector<int> nums;
for (int i = 1; i <= n; i++)
nums.push_back(i);
Inserting a value into a BST
A helper function add receives a subtree root and a value to insert. If the current root is null, a new node is allocated. Otherwise the function recurses left when the value is smaller than the node’s key, or right when it is greater or equal. The function returns the (possibly new) root of the subtree.
TreeNode* add(TreeNode* root, int value)
{
if (!root)
return new TreeNode(value);
if (value < root->val)
root->left = add(root->left, value);
else
root->right = add(root->right, value);
return root;
}
Serializing a BST to a canonical string
To compare trees for structural equality, the flatten routine produces a preorder-style string that records the presence of left and right children with the markers L and R, and inserts the node’s value between them. An empty subtree yields an empty string, ensuring that different shapes generate distinct serializations.
string flatten(TreeNode* root)
{
if (!root)
return "";
return "L" + flatten(root->left) + "V" + to_string(root->val) + "R" + flatten(root->right);
}
Enumerating permutations and building trees
The core loop uses next_permutation to walk through every ordering of the numbers. For each permutation, a fresh BST is built by repeatedly calling add. The resulting tree is then serialized, and the pair (serialization, root) is stored in a map. Because map keys are unique, any duplicate tree structures produced by different permutations automatically collapse to a single entry.
do
{
TreeNode* root = nullptr;
for (auto n : nums)
root = add(root, n);
trees[flatten(root)] = root;
} while (next_permutation(nums.begin(), nums.end()));
Extracting the distinct trees
After all permutations have been processed, the values of the map (the unique tree roots) are collected into a vector that forms the function’s return value.
vector<TreeNode*> result;
for (auto t : trees)
result.push_back(t.second);
return result;
Edge Cases Handled
When n equals 0, the initial loop that fills nums does not execute, leaving the vector empty. The subsequent do-while loop still runs once because do executes before the permutation check. Inside that iteration, the inner for loop over nums performs no insertions, leaving root as nullptr. The flatten call on a null pointer returns an empty string, which becomes the sole key in the map. Consequently, the function returns a vector containing a single nullptr, representing the empty tree case.
The add function gracefully handles insertion into an empty subtree by allocating a new node when the supplied root pointer is null. This ensures that the first element of any permutation always becomes the tree’s root without special-case code.
The serialization routine treats missing children uniformly: both left and right null pointers contribute nothing to the string, but the surrounding L and R markers remain, preserving the positional information of existing subtrees. This design prevents two different shapes from collapsing to the same string.
Performance Optimizations Observed
The algorithm leverages the standard library’s next_permutation, which generates permutations in lexicographic order using an in-place rearrangement of the nums vector. This avoids the overhead of constructing new containers for each ordering.
Insertion into the BST is performed recursively, reusing the same node objects for the duration of a single permutation’s construction. No intermediate containers are created to hold partial trees, reducing allocation churn.
Deduplication relies on a map keyed by the serialized representation. Because the map maintains sorted order, look-ups and insertions are logarithmic in the number of distinct trees encountered so far, providing a balanced trade-off between speed and memory usage compared with a naïve linear search.
The serialization function builds the string using concatenation of small literals and the result of recursive calls. Since each node contributes a fixed set of characters, the total work per tree scales linearly with the number of nodes, and the generated strings serve as compact identifiers for structural comparison.
Overall, the code combines standard library utilities with concise recursive helpers to achieve its goal without extraneous data structures or repeated traversals.
ELI5 - Simplified Explanation
Imagine you have a big box of numbered blocks. This computer code acts like a very organized builder who wants to see how many different ways those blocks can be stacked into a tree shape.
First, the builder takes all the numbers from one up to the number that you picked. The builder puts them in a line, almost like waiting in a row for a turn to play. Then, the builder picks up the first number and uses it to start a tree. Each friend after that looks at the tree and decides if they belong on the left side or the right side by checking if their number is smaller or bigger than the ones already there.
After the tree is finished, the builder takes a special picture of it by walking through it and writing down a secret code. This code shows exactly where every number is sitting. The builder does this over and over again, changing the order of the numbers in line every single time.
If the builder ever makes a tree that looks exactly like one already created, it just keeps the old one and moves on. Once all the different ways to line up the blocks have been tried, the finished collection of unique trees is gathered together into one big pile.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||||||
| www | AlgoMonster | C++ | Python | Java | TS | |||||||
| WalkCCC | C++ | Python | Java | |||||||||
| leetcode.ca | C++ | Python | Java | Rust | Go | TS | ||||||
| LeetcodeHelp | C++ | Python | Java | |||||||||
| MemoryLimitExceeded | C++ | Python | ||||||||||
| Progiez | C++ | Python | Java | |||||||||
| github | aylei | Rust | ||||||||||
| begeekmyfriend | C | |||||||||||
| BigEggStudy | C# | |||||||||||
| black-shadows | C++ | |||||||||||
| charles-wangkai | Java | |||||||||||
| chenyanzhe | C++ | |||||||||||
| everthis | JS | |||||||||||
| fartem | Ruby | |||||||||||
| fengvyi | C++ | |||||||||||
| fpdjsns | C++ | |||||||||||
| gaosq0604 | Python | |||||||||||
| Garvit244 | Python | |||||||||||
| gouthampradhan | Java | |||||||||||
| halfrost | Go | |||||||||||
| haoel | Python | |||||||||||
| JoshCrozier | JS | |||||||||||
| keineahnung2345 | C++ | |||||||||||
| lennylxx | C++ | |||||||||||
| linouk23 | C++ | |||||||||||
| lkwq007 | Python | |||||||||||
| luangong | C++ | |||||||||||
| MacJim | C++ | |||||||||||
| martianoff | Scala | |||||||||||
| qiyuangong | Python | |||||||||||
| ruoru | Rust | |||||||||||
| suxrobGM | C# | |||||||||||
| vthwang | Java | |||||||||||
| wisdompeak | C++ | |||||||||||
| zfang399 | C++ | |||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||||
| WalkCCC | C++, Python, Java | |||||||||||
| leetcode.ca | C++, Go, Java, Python, Rust, TypeScript | |||||||||||
| LeetcodeHelp | C++, Java, Python | |||||||||||
| MemoryLimitExceeded | Python, C++ | |||||||||||
| Progiez | C++, Java, Python | |||||||||||
| aylei | Rust | |||||||||||
| begeekmyfriend | C | |||||||||||
| BigEggStudy | C# | |||||||||||
| black-shadows | C++, C++ | |||||||||||
| charles-wangkai | Java | |||||||||||
| chenyanzhe | C++ | |||||||||||
| everthis | JavaScript | |||||||||||
| fartem | Ruby | |||||||||||
| fengvyi | C++ | |||||||||||
| fpdjsns | C++ | |||||||||||
| gaosq0604 | Python | |||||||||||
| Garvit244 | Python | |||||||||||
| gouthampradhan | Java | |||||||||||
| halfrost | Go | |||||||||||
| haoel | Python | |||||||||||
| JoshCrozier | JavaScript | |||||||||||
| keineahnung2345 | C++ | |||||||||||
| lennylxx | C++ | |||||||||||
| linouk23 | C++ | |||||||||||
| lkwq007 | Python | |||||||||||
| luangong | C++ | |||||||||||
| MacJim | C++ | |||||||||||
| martianoff | Scala | |||||||||||
| qiyuangong | Python | |||||||||||
| ruoru | Rust | |||||||||||
| suxrobGM | C# | |||||||||||
| vthwang | Java | |||||||||||
| wisdompeak | C++ | |||||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 96: Unique Binary Search Trees
Solved On The Same Day
- problem 1: Two Sum
- problem 9: Palindrome Number
- problem 14: Longest Common Prefix
- problem 20: Valid Parentheses
- problem 26: Remove Duplicates from Sorted Array
- problem 27: Remove Element
- problem 83: Remove Duplicates from Sorted List
- problem 88: Merge Sorted Array
- problem 94: Binary Tree Inorder Traversal
- problem 100: Same Tree
- problem 104: Maximum Depth of Binary Tree
- problem 121: Best Time to Buy and Sell Stock
- problem 136: Single Number
- problem 141: Linked List Cycle
- problem 169: Majority Element
- problem 190: Reverse Bits
- problem 226: Invert Binary Tree
- problem 234: Palindrome Linked List
- problem 1114: Print in Order
- problem 3: Longest Substring Without Repeating Characters
- problem 7: Reverse Integer
- problem 8: String to Integer (atoi)
- problem 11: Container With Most Water
- problem 12: Integer to Roman
- problem 15: 3Sum
- problem 17: Letter Combinations of a Phone Number
- problem 22: Generate Parentheses
- problem 31: Next Permutation
- problem 36: Valid Sudoku
- problem 39: Combination Sum
- problem 40: Combination Sum II
- problem 45: Jump Game II
- problem 46: Permutations
- problem 47: Permutations II
- problem 48: Rotate Image
- problem 49: Group Anagrams
- problem 55: Jump Game
- problem 59: Spiral Matrix II
- problem 75: Sort Colors
- problem 77: Combinations
- problem 91: Decode Ways
- problem 96: Unique Binary Search Trees
- problem 134: Gas Station
- problem 164: Maximum Gap
- problem 189: Rotate Array
- problem 215: Kth Largest Element in an Array
- problem 238: Product of Array Except Self
- problem 287: Find the Duplicate Number
- problem 322: Coin Change
- problem 347: Top K Frequent Elements
- problem 377: Combination Sum IV
- problem 438: Find All Anagrams in a String
- problem 474: Ones and Zeroes
- problem 518: Coin Change II
- problem 526: Beautiful Arrangement
- problem 763: Partition Labels
- problem 983: Minimum Cost For Tickets
- problem 994: Rotting Oranges
- problem 1027: Longest Arithmetic Subsequence
- problem 2140: Solving Questions With Brainpower
- problem 2466: Count Ways To Build Good Strings
- problem 4: Median of Two Sorted Arrays
- problem 41: First Missing Positive
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality