← Home

95. Unique Binary Search Trees II

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
dynamic programmingC++Markdown
95

A good way into this one is to ask: what do we need to remember so we never redo work blindly? For 95. Unique Binary Search Trees II, the solution in this repository is mainly a dynamic programming solution.

Guide

What?

The first job is to translate the English prompt into state, transition, and stopping conditions. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: dynamic programming, two pointers.

The notes already sitting in the source point us in the right direction:

  • recursion

Guide

When?

This is the kind of solution you want when the problem has structure hiding inside a messy-looking input. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are generateTrees, used, addOffset.

Guide

Why?

The win comes from making each line carry responsibility: store the useful state, discard the rest, keep moving.

  • The two-dimensional vector is the memory of the solution: grid state, DP state, or adjacency shape.
  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Read the setup variables first.
  2. Follow the main loop or recursive helper next.
  3. Watch where invalid states get skipped.
  4. Check which value survives to the return statement.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//recursion
02//Runtime: 36 ms, faster than 10.54% of C++ online submissions for Unique Binary Search Trees II.
03//Memory Usage: 18.2 MB, less than 5.04% of C++ online submissions for Unique Binary Search Trees II.
04/**
05 * Definition for a binary tree node.
06 * struct TreeNode {
07 *     int val;
08 *     TreeNode *left;
09 *     TreeNode *right;
10 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
11 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
12 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
13 * };
14 */
15class Solution {
16public:
17    int n;
18    
19    void generateTrees(vector<bool>& used, vector<TreeNode*>& trees){
20        for(int v = 1; v <= n; ++v){
21            if(used[v]) continue;
22            used[v] = true;
23            
24            vector<bool> lused = used;
25            vector<TreeNode*> ltrees;
26            //elements larger than v is not usable
27            for(int lv = v+1; lv <= n; ++lv){
28                lused[lv] = true;
29            }
30            generateTrees(lused, ltrees);
31            
32            vector<bool> rused = used;
33            vector<TreeNode*> rtrees;
34            for(int rv = 1; rv < v; ++rv){
35                rused[rv] = true;
36            }
37            generateTrees(rused, rtrees);
38            
39            // cout << "left: " << ltrees.size() << endl;
40            // cout << "right: " << rtrees.size() << endl;
41            
42            for(int li = 0; li < ltrees.size(); ++li){
43                for(int ri = 0; ri < rtrees.size(); ++ri){
44                    TreeNode* root = new TreeNode(v);
45                    root->left = ltrees[li];
46                    root->right = rtrees[ri];
47                    trees.push_back(root);
48                }
49            }
50            
51            used[v] = false;
52        }
53        if(trees.empty()) trees.push_back(nullptr);
54    }
55    
56    vector<TreeNode*> generateTrees(int n) {
57        if(n == 0) return {};
58        
59        this->n = n;
60        //0 is for padding
61        vector<bool> used(n+1, false);
62        vector<TreeNode*> trees;
63        
64        generateTrees(used, trees);
65        
66        return trees;
67    }
68};
69
70//recursion + memorization
71//note that a tree's range must be continuous, so we can use start and end to identify a tree
72//Runtime: 12 ms, faster than 95.32% of C++ online submissions for Unique Binary Search Trees II.
73//Memory Usage: 12.3 MB, less than 88.56% of C++ online submissions for Unique Binary Search Trees II.
74class Solution {
75public:
76    vector<vector<vector<TreeNode*>>> memo;
77    
78    void generateTrees(int start, int end){
79        // cout << start << " - " << end << endl;
80        
81        if(!memo[start][end].empty()){
82            return;
83        }
84        
85        if(start > end){
86            memo[start][end] = {nullptr};
87            return;
88        }
89        
90        vector<TreeNode*> trees;
91        for(int v = start; v <= end; ++v){
92            generateTrees(start, v-1);
93            vector<TreeNode*>& ltree = memo[start][v-1];
94            
95            generateTrees(v+1, end);
96            vector<TreeNode*>&rtree = memo[v+1][end];
97        
98            // cout << "left: " << ltrees.size() << endl;
99            // cout << "right: " << rtrees.size() << endl;
100            
101            for(int li = 0; li < ltree.size(); ++li){
102                for(int ri = 0; ri < rtree.size(); ++ri){
103                    TreeNode* root = new TreeNode(v);
104                    root->left = ltree[li];
105                    root->right = rtree[ri];
106                    trees.push_back(root);
107                }
108            }
109        }
110        if(trees.empty()) trees.push_back(nullptr);
111        memo[start][end] = trees;
112    }
113    
114    vector<TreeNode*> generateTrees(int n) {
115        if(n == 0) return {};
116        //[1,n] x [1,n] is valid range
117        //but 0 and n+1 are also used for convenience
118        memo = vector<vector<vector<TreeNode*>>>(n+2, 
119            vector<vector<TreeNode*>>(n+2));
120        generateTrees(1, n);
121        return memo[1][n];
122    }
123};
124
125//bottom-up DP
126//https://leetcode.com/problems/unique-binary-search-trees-ii/discuss/31493/Java-Solution-with-DP
127//Runtime: 20 ms, faster than 66.68% of C++ online submissions for Unique Binary Search Trees II.
128//Memory Usage: 12.8 MB, less than 83.42% of C++ online submissions for Unique Binary Search Trees II.
129class Solution {
130public:
131    TreeNode* addOffset(TreeNode* node, int offset){
132        /*
133        clone the whole tree rooted at "node",
134        but adding "offset" to all of its descendents
135        */
136        if(!node) return nullptr;
137        TreeNode* newnode = new TreeNode(node->val+offset);
138        
139        newnode->left = addOffset(node->left, offset);
140        newnode->right = addOffset(node->right, offset);
141        
142        return newnode;
143    }
144    
145    vector<TreeNode*> generateTrees(int n) {
146        if(n == 0) return {};
147        
148        vector<vector<TreeNode*>> dp(n+1);
149        
150        dp[0] = {nullptr};
151        
152        //count: size of tree
153        for(int count = 1; count <= n; ++count){
154            //val: root's value
155            for(int val = 1; val <= count; ++val){
156                // cout << count << ", " << val << endl;
157                for(TreeNode* ltree : dp[val-1]){
158                    for(TreeNode* rtree : dp[count-val]){
159                        TreeNode* node = new TreeNode(val);
160                        node->left = ltree;
161                        node->right = addOffset(rtree, val);
162                        dp[count].push_back(node);
163                    }
164                }
165            }
166        }
167        
168        return dp[n];
169    }
170};

Cost

Complexity

Time
O(n) to O(n log n), depending on the dominant loop or data structure operation
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.