question_slug
stringlengths
3
77
title
stringlengths
1
183
slug
stringlengths
12
45
summary
stringlengths
1
160
author
stringlengths
2
30
certification
stringclasses
2 values
created_at
stringdate
2013-10-25 17:32:12
2025-04-12 09:38:24
updated_at
stringdate
2013-10-25 17:32:12
2025-04-12 09:38:24
hit_count
int64
0
10.6M
has_video
bool
2 classes
content
stringlengths
4
576k
upvotes
int64
0
11.5k
downvotes
int64
0
358
tags
stringlengths
2
193
comments
int64
0
2.56k
unique-binary-search-trees-ii
✅Unique Binary Search Trees II || Recursion W/ Approach || C++ | Python
unique-binary-search-trees-ii-recursion-gik9v
Idea:\n We will use a recursive helper function that recieves a range (within n) and returns all subtrees in that range.\n We have a few cases:\n\t if start > e
Maango16
NORMAL
2021-09-02T18:22:13.210500+00:00
2021-09-02T18:22:13.210541+00:00
1,163
false
**Idea**:\n* We will use a recursive helper function that recieves a range `(within n)` and returns all subtrees in that range.\n* We have a few cases:\n\t* if `start > end`, which is not supposed to happen, we return a list that contains only a `null`.\n\t* if `start == end` it means we reached a `leaf` and we will return a `list containing a tree` that has only that node.\n\t* Otherwise:\n\t\t* for each option of root, we get `all possible subtrees` with that root for left and right children. Then for each possible pair of left and right we add to the result a new tree.\n\n**Solution**\n`In C++`\n```\nclass Solution {\npublic:\n vector<TreeNode*> rec(int start, int end) {\n vector<TreeNode*> res;\n if (start > end) return {NULL};\n if (start == end) return {new TreeNode(start)};\n for (int i = start; i <= end; i++) {\n vector<TreeNode*> left = rec(start, i-1), right = rec(i+1, end);\n for (auto l : left)\n for (auto r : right)\n res.push_back(new TreeNode(i, l, r));\n }\n return res;\n }\n \n vector<TreeNode*> generateTrees(int n) {\n vector<TreeNode*> res = rec(1, n);\n return res;\n }\n};\n```\n`In Python`\n```\nclass Solution:\n def generateTrees(self, n: int) -> List[TreeNode]:\n def rec(start, end):\n\t\t\n if start > end:\n return [None]\n\t\t\t\t\n if start == end:\n return [TreeNode(start)]\n ret_list = []\n\t\t\t\n for i in range(start, end+1):\n left = rec(start, i-1)\n right = rec(i+1, end)\n for pair in product(left, right):\n ret_list.append(TreeNode(i, pair[0], pair[1]))\n \n return ret_list\n \n res = rec(1,n)\n return res\n```
23
8
[]
5
unique-binary-search-trees-ii
[Python] divide and conquer with dp, explained
python-divide-and-conquer-with-dp-explai-qua3
We can use dp technique here, where in dp[i][j] we keep all possible trees from numbers i ... j. We can also keep only one dimensional dp, but then we need to c
dbabichev
NORMAL
2021-09-02T07:10:07.427399+00:00
2021-09-02T07:10:07.427461+00:00
1,172
false
We can use `dp` technique here, where in `dp[i][j]` we keep all possible trees from numbers `i ... j`. We can also keep only one dimensional `dp`, but then we need to `clone` trees, adding the same values to all elements. However, number of trees is exponential, and I think it is not worth to make this optimization from `O(n^2)` to `O(n)` memory, because problem can be solved for only small `n <= 50`.\n\n#### Complexity\nTime and space complexity is `O(C_{2n}^n)` approximately, because we have Catalan number of trees.\n\n#### Code\n```python\nclass Solution:\n def generateTrees(self, n):\n def dp(i, j):\n if i > j: return [None]\n ans = []\n \n for k in range(i, j + 1):\n for lft, rgh in product(dp(i, k-1), dp(k+1, j)):\n root = ListNode(k)\n root.left = lft\n root.right = rgh\n ans.append(root) \n return ans\n \n return dp(1, n)\n```\n\nIf you have any questions, feel free to ask. If you like solution and explanations, please **Upvote!**
23
2
['Divide and Conquer', 'Dynamic Programming']
3
unique-binary-search-trees-ii
C++ very easy to understand Recursive Solution
c-very-easy-to-understand-recursive-solu-vag1
\nclass Solution {\npublic:\n \n vector<TreeNode*> generateBST(int begin, int end)\n {\n vector<TreeNode*>V;\n \n if(begin>end)\n
chirags_30
NORMAL
2020-07-28T03:06:18.855904+00:00
2020-07-28T03:06:18.855938+00:00
2,882
false
```\nclass Solution {\npublic:\n \n vector<TreeNode*> generateBST(int begin, int end)\n {\n vector<TreeNode*>V;\n \n if(begin>end)\n {\n V.push_back(NULL);\n return V;\n }\n \n for(int i=begin; i<=end; i++)\n {\n vector<TreeNode*>left = generateBST(begin, i-1);\n vector<TreeNode*>right = generateBST(i+1,end);\n \n for(auto l:left)\n {\n for(auto r:right)\n {\n TreeNode* root = new TreeNode();\n root->val = i;\n root->left = l;\n root->right = r;\n V.push_back(root);\n }\n }\n \n }\n return V;\n }\n \n vector<TreeNode*> generateTrees(int n) {\n \n vector<TreeNode*>V;\n if(n==0) return V;\n \n return generateBST(1,n);\n }\n};\n```
23
1
['Recursion', 'C', 'C++']
4
unique-binary-search-trees-ii
Video Solution | 2 Approaches (Recursion + Memoization) | Intuition explained in detail
video-solution-2-approaches-recursion-me-nx8l
\n# Video\n Describe your first thoughts on how to solve this problem. \nHey everyone, i have created a video solution for this problem (it\'s in hindi), wher
_code_concepts_
NORMAL
2024-08-17T06:43:20.637873+00:00
2024-08-17T06:43:20.637910+00:00
1,721
false
\n# Video\n<!-- Describe your first thoughts on how to solve this problem. -->\nHey everyone, i have created a video solution for this problem (it\'s in hindi), where i have explained the video from very basic intuition to optimal approach, which means there are in total 2 approches:\n- Recursion\n- Memoization (DP)\n\nthis video is part of my trees playlist, do watch till the end for complete and concise explanation.\n\nVideo link: https://youtu.be/88OdfKao_Uw\nPlaylist link: https://www.youtube.com/playlist?list=PLICVjZ3X1Aca0TjUTcsD7mobU001CE7GL\n\n# Code\n```\n/**\n * Definition for a binary tree node.\n * struct TreeNode {\n * int val;\n * TreeNode *left;\n * TreeNode *right;\n * TreeNode() : val(0), left(nullptr), right(nullptr) {}\n * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}\n * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}\n * };\n */\nclass Solution {\npublic:\n vector<vector<vector<TreeNode*>>> memo;\n\n vector<TreeNode*> helper(int start, int end){\n // BC\n vector<TreeNode*> ans;\n if(start>end){\n ans.push_back(NULL);\n return ans;\n }\n if(!memo[start][end].empty()) return memo[start][end];\n\n for(int i=start;i<=end;i++){\n //RR\n vector<TreeNode*> leftSub= helper(start,i-1);\n vector<TreeNode*> rightSub= helper(i+1,end);\n for(auto lt:leftSub){\n for(auto rt:rightSub){\n // TASK\n TreeNode* root= new TreeNode(i);\n\n root->left=lt;\n root->right= rt;\n ans.push_back(root);\n }\n }\n\n }\n memo[start][end] = ans;\n return ans;\n }\n vector<TreeNode*> generateTrees(int n) {\n\n memo = vector<vector<vector<TreeNode*>>>(n + 1, vector<vector<TreeNode*>>(n + 1));\n\n vector<TreeNode*> res= helper(1,n);\n memo.clear();\n return res;\n\n \n }\n};\n```
21
0
['C++']
2
unique-binary-search-trees-ii
[Python] Recursive solution explained (beats 99.56%)
python-recursive-solution-explained-beat-rd0o
The basic idea is to recursively split the conceptual array [1, ..., n] in half. During every split, make a new root node for every different combination of lef
m-just
NORMAL
2020-03-11T08:02:41.666231+00:00
2020-03-23T07:15:26.564507+00:00
3,329
false
The basic idea is to recursively split the conceptual array `[1, ..., n]` in half. During every split, make a new root node for every different combination of left/right subtree structures. For the time complexity of this algorithm, please check the comment below.\n```python\ndef generateTrees(self, n: int) -> List[TreeNode]:\n def generate(l, r): # split between [l, r)\n if l == r:\n return [None]\n nodes = []\n for i in range(l, r):\n for lchild in generate(l, i):\n for rchild in generate(i+1, r):\n node = TreeNode(i+1) # +1 to convert the index to the actual value\n node.left = lchild\n node.right = rchild\n nodes.append(node)\n return nodes\n return generate(0, n) if n else []\n```\nVote up if you find this helpful, thanks!
21
2
['Recursion', 'Python', 'Python3']
3
unique-binary-search-trees-ii
30 ms c++ solution
30-ms-c-solution-by-pankit-fl9v
/**\n * Definition for binary tree\n * struct TreeNode {\n * int val;\n * TreeNode *left;\n * TreeNode *right;\n * TreeN
pankit
NORMAL
2015-02-26T02:19:51+00:00
2018-09-14T20:15:36.868602+00:00
4,193
false
/**\n * Definition for binary tree\n * struct TreeNode {\n * int val;\n * TreeNode *left;\n * TreeNode *right;\n * TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\n class Solution {\n public:\n vector<TreeNode *> generateTrees(int n) {\n return helper(1,n);\n }\n \n vector<TreeNode*> helper(int s, int e) {\n if (s > e) {\n return vector<TreeNode*>(1,NULL);\n }\n \n vector<TreeNode*> result;\n for (int i=s; i <= e; ++i) {\n vector<TreeNode*> left, right;\n left = helper(s,i-1);\n right = helper(i+1,e);\n for (int j = 0; j < left.size(); ++j) {\n for (int k = 0; k < right.size(); ++k) {\n TreeNode* root = new TreeNode(i);\n root->left = left[j];\n root->right = right[k];\n result.push_back(root);\n }\n }\n }\n \n return result;\n }\n };
21
1
[]
7
unique-binary-search-trees-ii
20ms C++ top-down DP solution
20ms-c-top-down-dp-solution-by-ragepyre-rvvq
a bottom up solution looks much better, but I find it's also a little bit harder to understand. Top-down solution is straight forward,\n\n \n\n vector gene
ragepyre
NORMAL
2015-06-26T19:14:46+00:00
2015-06-26T19:14:46+00:00
4,776
false
a bottom up solution looks much better, but I find it's also a little bit harder to understand. Top-down solution is straight forward,\n\n \n\n vector<TreeNode*> generateTrees(int n) {\n vector<TreeNode*> ret;\n vector<vector<vector<TreeNode*>>> dp(n,vector<vector<TreeNode*>>(n));\n helper(1,n,ret,dp);\n return ret;\n }\n \n void helper(int start, int end, vector<TreeNode*> &ret,vector<vector<vector<TreeNode*>>> &dp) {\n if (start > end) {\n ret.push_back(NULL); return;\n }\n if (!dp[start-1][end-1].empty()) {\n ret = dp[start-1][end-1]; return;\n }\n for (int i = start; i <= end; ++i) {\n vector<TreeNode*> left, right;\n helper(start, i-1,left,dp);\n helper(i+1,end,right,dp);\n for(int j = 0; j < left.size(); ++j) {\n for (int k = 0; k < right.size(); ++k) {\n TreeNode* node = new TreeNode(i);\n node->left = left[j];\n node->right = right[k];\n ret.push_back(node);\n }\n }\n }\n dp[start-1][end-1] = ret;\n }
18
0
['Dynamic Programming', 'Memoization']
3
unique-binary-search-trees-ii
Beats 100% + Video | Java C++ Python
beats-100-video-java-c-python-by-jeevank-umq8
\n\n\nclass Solution {\n Map<Pair<Integer, Integer>, List<TreeNode>> dp; \n public List<TreeNode> generateTrees(int n) {\n dp = new HashMap<>();\n
jeevankumar159
NORMAL
2023-08-05T02:44:29.846398+00:00
2023-08-05T02:44:29.846432+00:00
3,123
false
<iframe width="560" height="315" src="https://www.youtube.com/embed/4Ca9t6LYRDI" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe>\n\n```\nclass Solution {\n Map<Pair<Integer, Integer>, List<TreeNode>> dp; \n public List<TreeNode> generateTrees(int n) {\n dp = new HashMap<>();\n return helper(1, n);\n }\n \n public List<TreeNode> helper(int start, int end) {\n List<TreeNode> variations = new ArrayList<>();\n if (start > end) {\n variations.add(null);\n return variations;\n }\n if (dp.containsKey(new Pair<>(start, end))) {\n return dp.get(new Pair<>(start, end));\n }\n for (int i = start; i <= end; ++i) {\n List<TreeNode> leftSubTrees = helper(start, i - 1);\n List<TreeNode> rightSubTrees = helper(i + 1, end);\n for (TreeNode left: leftSubTrees) {\n for (TreeNode right: rightSubTrees) {\n TreeNode root = new TreeNode(i, left, right);\n variations.add(root);\n }\n }\n }\n dp.put(new Pair<>(start, end), variations);\n return variations;\n } \n}\n```\n\n```\nclass Solution {\npublic:\n map<pair<int, int>, vector<TreeNode*>> dp; \n \n vector<TreeNode*> generateTrees(int n) {\n return helper(1, n);\n }\n \n vector<TreeNode*> helper(int start, int end) {\n vector<TreeNode*> variations;\n if (start > end) {\n variations.push_back(nullptr);\n return variations;\n }\n if (dp.find(make_pair(start, end)) != dp.end()) {\n return dp[make_pair(start, end)];\n }\n for (int i = start; i <= end; ++i) {\n vector<TreeNode*> leftSubTrees = helper(start, i - 1);\n vector<TreeNode*> rightSubTrees = helper(i + 1, end);\n for (TreeNode* left : leftSubTrees) {\n for (TreeNode* right : rightSubTrees) {\n TreeNode* root = new TreeNode(i);\n root->left = left;\n root->right = right;\n variations.push_back(root);\n }\n }\n }\n dp[make_pair(start, end)] = variations;\n return variations;\n }\n};\n\n```\n\n```\nclass Solution:\n def generateTrees(self, n: int) -> List[TreeNode]:\n def helper(start, end):\n variations = []\n if start > end:\n variations.append(None)\n return variations\n if (start, end) in dp:\n return dp[(start, end)]\n for i in range(start, end + 1):\n leftSubTrees = helper(start, i - 1)\n rightSubTrees = helper(i + 1, end)\n for left in leftSubTrees:\n for right in rightSubTrees:\n root = TreeNode(i)\n root.left = left\n root.right = right\n variations.append(root)\n dp[(start, end)] = variations\n return variations\n \n dp = {}\n return helper(1, n)\n\n```
16
3
['C', 'Python', 'Java']
0
unique-binary-search-trees-ii
6 Liner C++ Recursive
6-liner-c-recursive-by-amitpandey31-v7l1
\nclass Solution {\npublic:\n vector<TreeNode*> generateTrees(int n, int s = 1) {\n vector<TreeNode*> ans;\n if(n < s) return {nullptr};
AmitPandey31
NORMAL
2022-08-30T07:26:29.241226+00:00
2022-08-31T17:31:11.373891+00:00
2,184
false
```\nclass Solution {\npublic:\n vector<TreeNode*> generateTrees(int n, int s = 1) {\n vector<TreeNode*> ans;\n if(n < s) return {nullptr}; \n for(int i=s; i<=n; i++) { \t // Consider every number in range [s,n] as root \n for(auto left: generateTrees(i-1, s)) { // generate all possible trees in range [s,i)\n for(auto right: generateTrees(n, i+1)) // generate all possible trees in range (i,e]\n ans.push_back(new TreeNode(i, left, right)); // make new trees with i as the root\n }\n }\n return ans;\n }\n};\n```\n**Please Upvote \nthank you**
15
0
['Recursion', 'C', 'C++']
0
unique-binary-search-trees-ii
[Java] Recursion & Iteration Solutions (DP, Clone, Memoization)
java-recursion-iteration-solutions-dp-cl-k2x7
Reference: LeetCode\nDifficulty: Medium\n\n## Problem\n\n> Given an integer n, generate all structurally unique BST\'s (binary search trees) that store values 1
junhaowanggg
NORMAL
2019-10-21T06:58:45.484098+00:00
2019-10-21T06:59:37.499329+00:00
1,368
false
Reference: [LeetCode](https://leetcode.com/problems/unique-binary-search-trees-ii/)\nDifficulty: <span class="orange">Medium</span>\n\n## Problem\n\n> Given an integer `n`, generate all structurally unique BST\'s (binary search trees) that store values `1 ... n`.\n\n**Example:**\n\n```java\nInput: 3\nOutput:\n[\n [1,null,3,2],\n [3,2,null,1],\n [3,1,null,null,2],\n [2,1,3],\n [1,null,2,null,3]\n]\nExplanation:\nThe above output corresponds to the 5 unique BST\'s shown below:\n\n 1 3 3 2 1\n \\ / / / \\ \\\n 3 2 1 1 3 2\n / / \\ \\\n 2 1 2 3\n```\n\n\n## Analysis\n\n### Recursion\n\nIf we directly apply the solution in `96. Unique Binary Search Trees`, we have an incorrect result. Consider the following example.\n\n```java\nn = 5, i = 3\n2 left nodes: [1, 2]\n2 right nodes: [4, 5]\n\nn = 10, i = 8\n7 left nodes: [1, 2, 3, 4, 5, 6, 7]\n2 right nodes: [9, 10]\n```\n\nAs you can see, although there are still 2 nodes in the right subtrees, the values are not the same. In the previous approach, it did not handle this situation.\n\nSo rather than passing a parameter `n` (number of nodes), we now pass down two parameters `lo` and `hi` indicating the range of values of a tree.\n\nFor example, `generateTrees(1, 5)` generate trees whose values range from `1` to `5`, and each of them has a chance to be the root, which also includes the information of number of nodes `n`. Say when the root is `3`, we calculate `generateTrees(1, 2)` and `generateTrees(4, 5)`.\n\n**Note:** When `n == 0`, it returns `[]` instead of `[[null]]`.\n\n```java\npublic List<TreeNode> generateTrees(int n) {\n if (n == 0) {\n return new ArrayList<>();\n }\n return generateTrees(1, n);\n}\n\nprivate List<TreeNode> generateTrees(int lo, int hi) {\n int n = hi - lo + 1;\n if (n == 0) {\n List<TreeNode> L = new ArrayList<>();\n L.add(null);\n return L;\n }\n List<TreeNode> result = new ArrayList<>();\n for (int i = lo; i <= hi; ++i) {\n List<TreeNode> leftSubtrees = generateTrees(lo, i - 1);\n List<TreeNode> rightSubtrees = generateTrees(i + 1, hi);\n for (TreeNode leftSub : leftSubtrees) {\n for (TreeNode rightSub : rightSubtrees) {\n TreeNode newTree = new TreeNode(i);\n newTree.left = leftSub;\n newTree.right = rightSub;\n result.add(newTree);\n }\n }\n }\n return result;\n}\n```\n\n**Time:** It is at most bounded by `O(N x N!)`. A tighter bound would be Catalan number times `N` since we\'ve done `N` times, which is `N x G_N = O(Nx\\frac{4^N}{N^{3/2}}) = O(\\frac{4^N}{N^{1/2}})`.\n**Space:** `O(N x G_N) = O(\\frac{4^N}{N^{1/2}})`\n\n\n\n### DP (Clone)\n\nReference: [link](https://leetcode.wang/leetCode-95-Unique-Binary-Search-TreesII.html)\n\nLet\'s denote `tree[i]` as the list of trees of size `i`. Think of `tree[i]` as our building blocks for a larger tree.\n\n```java\nExample: n = 3\n\ntree[0]:\nnull\n\ntree[1]:\n[1]\n[2]\n[3]\n\ntree[2]:\n[1 2]\n1\n \\\n 2 // 2 structures\n 2\n /\n1\n[2 3]\n2\n \\\n 3\n 3\n /\n2 // [1 3] is not possible\n\ntree[3]: // (based on tree[1], tree[2])\n 3\n /\n[1 2]\n 1\n \\\n [2 3]\n 2\n / \\\n[1] [3]\n```\n\nSo we can compute all possible trees for `tree[1]`, `tree[2]`, ..., then we can construct `tree[n]` by previous results.\n\nFor a small `n = 3` , we notice that when we calculate `tree[2]` we want all possible combinations for `tree[2]` (`[1 2]`, `[2 3]`). **Furthermore**, if we have a large `n = 100`, we want all the combinations as follows `[1 2]`, `[2 3]`, `[3 4]`, ..., `[99 100]` (each of them has two structures).\n\nSince these trees have the same two types of structures:\n\n```java\nx y\n \\ /\n y x\n```\n\nWe can actually construct all the trees by `[1 2]` plus some constant, say `offset`. For example, `[5 6]` can be constructed as follows:\n\n```java\n1 +4 5\n \\ \\\n 2 +4 6\n------------------\n 2 +4 6\n / /\n1 +4 5\n```\n\nSay the problem is `n = 100`. During the execution of the algorithm when `i = 98`, we want to get all possible trees for `i = 98` as the root. The size of the left subtree is `97` and the subtree is picked from `tree[97]`; the size of the right subtree is `2` and the subtree is picked from `tree[2]`.\n\nFor the left subtree, we already have `tree[97]` computed as `[1 2 3 ... 97]`.\n\nFor the right subtree, we want `[99 100]`, which can be computed by `[1 2]` plus `offset = 98`.\n\n```java\n1 +98 99\n \\ \\\n 2 +98 100\n------------------\n 2 +98 100\n / /\n1 +98 99\n```\n\nTherefore, given a tree `root`, we can generate a new tree by cloning with an `offset`.\n\n```java\n// adding offset to each node of a tree root\nprivate TreeNode clone(TreeNode root, int offset) {\n if (n == null) {\n return null;\n }\n TreeNode node = new TreeNode(root.val + offset);\n node.left = clone(root.left, offset);\n node.right = clone(root.right, offset);\n return node;\n}\n```\n\nFor input `n`, the result we want is `tree[n]` (`[1 2 3 ... n]`). Here is the code for `generateTrees(n)`:\n\n```java\npublic List<TreeNode> generateTrees(int n) {\n List<TreeNode>[] tree = new ArrayList[n + 1];\n tree[0] = new ArrayList<>();\n if (n == 0) {\n return tree[0];\n }\n tree[0].add(null);\n // Calculate all lengths\n for (int len = 1; len <= n; ++len) {\n tree[len] = new ArrayList<>(); // contains all trees we construct\n // Consider each as the root\n for (int i = 1; i <= len; ++i) {\n int leftSize = i - 1;\n int rightSize = len - i;\n for (TreeNode leftTree : tree[leftSize]) [\n for (TreeNode rightTree : tree[rightSize]) {\n TreeNode tree = new TreeNode(i);\n tree.left = leftTree; // left subtree requires no cloning\n tree.right = clone(rightTree, i); // add i as the offset\n tree[len].add(tree);\n }\n ]\n }\n }\n return tree[n];\n}\n```\n\n**Time:** <span class="purple">N/A</span> (I don\'t know T_T)\n**Space:** <span class="purple">N/A</span> (I don\'t know T_T)\n\n\n### DP (2D)\n\nJudge: `1ms`, faster than `99.95%`. I have nothing to say.\n\n![](https://bloggg-1254259681.cos.na-siliconvalley.myqcloud.com/sz3zr.jpg)\n\nHere is the code I wrote:\n\n```java\npublic List<TreeNode> generateTrees(int n) {\n if (n == 0) {\n return new ArrayList<>();\n }\n List<TreeNode>[][] g = new ArrayList[n + 1][n + 1];\n // init\n List<TreeNode> nullList = new ArrayList<>(); nullList.add(null);\n g[0][0] = nullList;\n for (int k = 1; k <= n; ++k) { // g(0, k)\n g[0][k] = nullList;\n }\n for (int k = 1; k <= n; ++k) { // diagonal: one node (itself)\n List<TreeNode> oneList = new ArrayList<>(); oneList.add(new TreeNode(k));\n g[k][k] = oneList;\n }\n for (int k = 1; k <= n; ++k) { // one node above diagonal: nullList\n g[k][k - 1] = nullList;\n }\n // dp\n for (int i = n - 1; i >= 1; --i) {\n for (int j = i + 1; j <= n; ++j) {\n List<TreeNode> result = new ArrayList<>();\n for (int k = i ; k <= j; ++k) { // for each k as root [i, j]\n List<TreeNode> leftList = (k - 1 <= n) ? g[i][k - 1] : nullList;\n List<TreeNode> rightList = (k + 1 <= n) ? g[k + 1][j] : nullList;\n for (TreeNode left : leftList) {\n for (TreeNode right: rightList) {\n TreeNode newTree = new TreeNode(k);\n newTree.left = left;\n newTree.right = right;\n result.add(newTree);\n }\n }\n }\n g[i][j] = result;\n }\n }\n return g[1][n];\n}\n```\n\n**Time:** <span class="purple">N/A</span> (I don\'t know T_T)\n**Space:** <span class="purple">N/A</span> (I don\'t know T_T)
15
1
['Dynamic Programming', 'Recursion', 'Memoization', 'Java']
0
unique-binary-search-trees-ii
An Intuitive Explanation with Diagrams
an-intuitive-explanation-with-diagrams-b-e9ei
BASICS\nBST? A node x has node z to right with value z>x and node y to the left with y<x.\n\n\n\nBUILDING THE INTUITION: OBSERVATIONS\n- n = 1 case is trivial\n
chaudhary1337
NORMAL
2021-09-02T09:20:16.709976+00:00
2021-09-02T09:26:15.079863+00:00
614
false
***BASICS***\nBST? A node `x` has node `z` to right with value `z>x` and node `y` to the left with `y<x`.\n\n![image](https://assets.leetcode.com/users/images/3c9045fe-eaed-456a-a20b-3bcb09a6b4a2_1630574055.9780717.png)\n\n***BUILDING THE INTUITION: OBSERVATIONS***\n- n = 1 case is trivial\n- n = 2 case suggests\n\t- either swapping is important\n\t- or, changing the root is\n![image](https://assets.leetcode.com/users/images/3f9339f0-279e-42fa-80b9-66d0c40b0939_1630574123.1668983.png)\n\n- n = 3 shows us:\n\t- swapping idea is too complex for > 2 nodes\n\t- the root idea works out better, we can **recursively** find the subtrees\n\t- there are repeating structures **DP**\n![image](https://assets.leetcode.com/users/images/1757d47f-d667-4c66-9d4d-cbc0c621b197_1630574306.0539086.png)\n\n***SAMPLE CASE***\nConsider the case: curr is 4. We split into left and right parts - for which we will call a recursive function again. I have considered the right sub-tree case:\n![image](https://assets.leetcode.com/users/images/0af12d87-261d-4af0-9b5e-1085b58882c7_1630574322.4836857.png)\n\nEach recursion returns the total number of BSTs formed.\n\n***CODE***\n```\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def generateTrees(self, n: int) -> List[Optional[TreeNode]]:\n \n @lru_cache(None)\n def recurse(l, r):\n if l > r: return [None]\n trees = []\n for i in range(l, r+1):\n lefts = recurse(l, i-1)\n rights = recurse(i+1, r)\n \n for left in lefts:\n for right in rights:\n tree = TreeNode(i)\n tree.left = left\n tree.right = right\n trees.append(tree)\n \n return trees\n \n return recurse(1, n)\n```\n\n**Upvote if this helps! It gives me feedback :)**
14
1
[]
1
unique-binary-search-trees-ii
C++ || Recursion || Day 5
c-recursion-day-5-by-chiikuu-gljb
Code\n\n/**\n * Definition for a binary tree node.\n * struct TreeNode {\n * int val;\n * TreeNode *left;\n * TreeNode *right;\n * TreeNode() :
CHIIKUU
NORMAL
2023-08-05T09:12:32.615217+00:00
2023-08-05T09:13:17.681987+00:00
3,027
false
# Code\n```\n/**\n * Definition for a binary tree node.\n * struct TreeNode {\n * int val;\n * TreeNode *left;\n * TreeNode *right;\n * TreeNode() : val(0), left(nullptr), right(nullptr) {}\n * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}\n * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}\n * };\n */\nclass Solution {\npublic:\n vector<TreeNode*> generateTree(int size,int s,int e) {\n if(size==0){\n return {NULL};\n }\n if(size==1){\n TreeNode* temp = new TreeNode(s);\n return {temp};\n }\n vector<TreeNode*>ans;\n for(int i=s;i<=e;i++){\n vector<TreeNode*>v1 = generateTree(i-s,s,i-1);\n vector<TreeNode*>v2 = generateTree(e-i,i+1,e);\n for(int j=0;j<v1.size();j++){\n for(int k=0;k<v2.size();k++){\n TreeNode* temp = new TreeNode(i);\n temp->left = v1[j];\n temp->right = v2[k];\n ans.push_back(temp);\n }\n } \n }\n return ans;\n }\n vector<TreeNode*> generateTrees(int n) {\n return generateTree(n,1,n);\n }\n};\n```\n![upvote (2).jpg](https://assets.leetcode.com/users/images/abcf0777-a48c-4c76-ab0a-0c126e6b8ca7_1691226748.0385122.jpeg)\n
13
0
['Tree', 'Binary Search Tree', 'Recursion', 'C++']
4
unique-binary-search-trees-ii
C++ Easy Recursive Solution
c-easy-recursive-solution-by-mythri_kaul-rmzj
Let us start by understanding how many unique BSTs are possible for keys 1-n.\n\nTo form a structurally unique BST of n nodes, we can take any of the 1-n keys a
Mythri_Kaulwar
NORMAL
2021-11-08T07:32:10.699930+00:00
2021-11-08T07:34:31.543216+00:00
1,048
false
Let us start by understanding how many unique BSTs are possible for keys 1-n.\n\nTo form a structurally unique BST of n nodes, we can take any of the 1-n keys as the root. Let us take key i (1<=i<=n) as the root. Now the left subtrees can contain nodes with keys 1 to i-1 (Since all the values in the left subtree must be smaller than that in the root) and the right subtrees can contain nodes with keys i+1 to n. \nFor example if n=3, i can be 1 (or) 2 (or) 3\n```\n 1 1 2 3 3\n\t\\ \\ / \\ / /\n\t 3 2 1 3 2 1\n / \\ / \\\n 2 3 1 2\n i = 1 i = 2 i = 3 \n```\nSo, to construct a BST with a given root, we need to know the number of possible left subtrees(LSTs) and number of possible right subtrees(RSTs).\nLet the no. possible LSTs be *numTrees(i-1)* and no. of possible BSTs be *numTrees(n-i)* . So the total no. of BSTs possible when i is the root are : *numTrees(i-1) * numTrees(n-i)*\n\n**Code :**\n```\nclass Solution {\npublic:\n vector<TreeNode*> constructTrees(int start, int end){\n vector<TreeNode*> result;\n\t\t\n if(start==end){\n TreeNode *root = new TreeNode(start);\n result.push_back(root);\n return result;\n }\n if(start>end){\n result.push_back(NULL);\n return result;\n }\n \n for(int i=start;i<=end;i++){\n vector<TreeNode*> leftTrees = constructTrees(start, i-1); /*Total no. of LSTs possible when is the root*/\n vector<TreeNode*> rightTrees = constructTrees(i+1, end); \n\t\t\t/*Join each left and right subtree to the root to form different BSTs*/\n for(auto l: leftTrees){\n for(auto r: rightTrees){\n TreeNode *root = new TreeNode(i); \n root->left = l;\n root->right = r;\n result.push_back(root); /*Add the root of the resulting BST each time to the vector result*/\n }\n }\n }\n return result;\n \n }\n vector<TreeNode*> generateTrees(int n) {\n return constructTrees(1, n);\n }\n};\n```\n\nPlease upvote if u like the solution\uD83D\uDE4F\n
13
0
['Recursion', 'C', 'C++']
1
unique-binary-search-trees-ii
Sharing top-down DP Python solution, beats 93.33%
sharing-top-down-dp-python-solution-beat-my2r
def generateTrees(self, n):\n \n def gen_trees(s, e, memo):\n if e < s:\n return [None]\n ret_list = []\n
agave
NORMAL
2016-04-06T02:30:47+00:00
2018-10-13T00:32:38.631220+00:00
1,856
false
def generateTrees(self, n):\n \n def gen_trees(s, e, memo):\n if e < s:\n return [None]\n ret_list = []\n if (s, e) in memo:\n return memo[s, e]\n for i in range(s, e + 1):\n list_left = gen_trees(s, i - 1, memo)\n list_right = gen_trees(i + 1, e, memo)\n for left in list_left:\n for right in list_right:\n root = TreeNode(i)\n root.left = left\n root.right = right\n ret_list.append(root)\n memo[s, e] = ret_list\n return ret_list\n \n if n == 0:\n return []\n return gen_trees(1, n, {})
13
0
['Dynamic Programming', 'Memoization']
3
unique-binary-search-trees-ii
C++ || Recursion
c-recursion-by-abhay5349singh-62yd
Connect with me on LinkedIn: https://www.linkedin.com/in/abhay5349singh/\n\n\n\n\n/**\n * Definition for a binary tree node.\n * struct TreeNode {\n * int v
abhay5349singh
NORMAL
2023-08-05T01:57:28.169455+00:00
2023-08-05T02:06:30.411720+00:00
1,775
false
**Connect with me on LinkedIn**: https://www.linkedin.com/in/abhay5349singh/\n\n![image](https://assets.leetcode.com/users/images/5be019ea-898c-4178-b92a-afdd521465c9_1691201173.537878.jpeg)\n\n```\n/**\n * Definition for a binary tree node.\n * struct TreeNode {\n * int val;\n * TreeNode *left;\n * TreeNode *right;\n * TreeNode() : val(0), left(nullptr), right(nullptr) {}\n * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}\n * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}\n * };\n */\nclass Solution {\npublic:\n \n vector<TreeNode*> build(int start, int end){\n if(start>end) return {NULL};\n if(start==end) return {new TreeNode(start)};\n \n vector<TreeNode*> ans;\n for(int i=start;i<=end;i++){\n // inorder of BST is sorted i.e left -> root-> right\n vector<TreeNode*> left=build(start,i-1);\n vector<TreeNode*> right=build(i+1,end);\n \n // building all possible combinations with left having smaller than root & right having bigger values than root\n for(TreeNode* l : left){\n for(TreeNode* r : right){\n TreeNode* root=new TreeNode(i);\n root->left=l;\n root->right=r;\n \n ans.push_back(root);\n }\n }\n }\n return ans;\n }\n \n vector<TreeNode*> generateTrees(int n) {\n return build(1,n);\n }\n};\n```\n\n**Do upvote if it helps :)**
12
2
['Recursion', 'C++']
1
unique-binary-search-trees-ii
✔️ 100% Fastest Swift Solution
100-fastest-swift-solution-by-sergeylesc-tnlh
\n/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * public var val: Int\n * public var left: TreeNode?\n * public var right
sergeyleschev
NORMAL
2022-04-08T13:30:55.221356+00:00
2022-04-08T13:30:55.221406+00:00
694
false
```\n/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * public var val: Int\n * public var left: TreeNode?\n * public var right: TreeNode?\n * public init() { self.val = 0; self.left = nil; self.right = nil; }\n * public init(_ val: Int) { self.val = val; self.left = nil; self.right = nil; }\n * public init(_ val: Int, _ left: TreeNode?, _ right: TreeNode?) {\n * self.val = val\n * self.left = left\n * self.right = right\n * }\n * }\n */\n\nclass Solution {\n func generateTrees(_ n: Int) -> [TreeNode?] {\n var nums: [Int] = []\n \n func copyNodes(_ node: TreeNode?, _ left: TreeNode?, _ right: TreeNode?) -> TreeNode? {\n if node == nil { return nil } \n else {\n let newNode = TreeNode(node!.val)\n newNode.left = copyNodes(left, left?.left, left?.right)\n newNode.right = copyNodes(right, right?.left, right?.right)\n return newNode\n }\n }\n\n func generateNodes(_ node: TreeNode?, _ left: [TreeNode?], _ right: [TreeNode?]) -> [TreeNode?] {\n let leftCount = left.count > 0 ? left.count : 1\n let rightCount = right.count > 0 ? right.count : 1\n var res: [TreeNode?] = []\n \n for i in 0..<leftCount {\n let leftNode = left.count > 0 ? left[i] : nil\n for j in 0..<rightCount {\n let rightNode = right.count > 0 ? right[j] : nil\n res.append(copyNodes(node, leftNode, rightNode))\n }\n }\n return res\n }\n\n func nodes(_ nums: [Int]) -> [TreeNode?] {\n if nums.count == 0 { return [] }\n var res: [TreeNode?] = []\n\n for (i, num) in nums.enumerated() {\n let node = TreeNode(num)\n let leftNodes = i > 0 ? nodes(Array(nums[0..<i])) : nodes([])\n let rightNodes = i < nums.count - 1 ? nodes(Array(nums[i + 1...nums.count - 1])) : nodes([])\n res += generateNodes(node, leftNodes, rightNodes)\n }\n return res\n }\n \n for num in 1...n { nums.append(num) }\n return nodes(nums)\n }\n\n}\n```\n\nLet me know in comments if you have any doubts. I will be happy to answer.\n\nPlease upvote if you found the solution useful.
12
0
['Swift']
2
unique-binary-search-trees-ii
Explanation with diagrams,DP solution.
explanation-with-diagramsdp-solution-by-6w02n
Again I am going to explain a DP solution using diagrams.\nFirst I define a two-dimension list res[0..n][0..n].(res[0][0] is of no use,just for readability,so w
planegoose
NORMAL
2019-07-11T14:33:42.723872+00:00
2019-07-11T14:33:42.723907+00:00
656
false
Again I am going to explain a DP solution using diagrams.\nFirst I define a two-dimension list res[0..n][0..n].(res[0][0] is of no use,just for readability,so we will ignore them later.)\nres[i][j] stores the root TreeNode of all possible BST formed by integers from i to j.Then our goal is res[1][n].\nTo calculate res[1][n],we can review last problem,to find out the recursion formula.\nTake n=3 into consideration first,we want to know res[1][3].\n![image](https://assets.leetcode.com/users/planegoose/image_1562855139.png)\n\n![image](https://assets.leetcode.com/users/planegoose/image_1562855122.png)\nFrom the picture we can find that solving res[1][3] needs res[2][3],res[1][1],res[3][3] and res[1][2].\n![image](https://assets.leetcode.com/users/planegoose/image_1562855224.png)\n\nTo be specific,for instance,if we have known res[2][3],by simply set \n```\nfor oneNode of res[2][3] :\n t = TreeNode(1)\n t.left = null\n t.right = oneNode\n res[1][3].append(t)\n```\nwe can get some possible solution of res[1][3].By the same method we can solve out all solutions of res[1][3].\nThen we turn to res[2][3].As is the same,res[2][3] rely on res[2][2] and res[3][3]\n,and res[1][2] rely on res[1][1] and res[2][2].\n![image](https://assets.leetcode.com/users/planegoose/image_1562855195.png)\n![image](https://assets.leetcode.com/users/planegoose/image_1562855252.png)\nIt is obvious that res[i][i] = [i].\nSo we only need to fill the matrix along every diagonal line one by one,from middle diagonal line to the right-top corner.\n![image](https://assets.leetcode.com/users/planegoose/image_1562855271.png)\n![image](https://assets.leetcode.com/users/planegoose/image_1562855278.png)\n![image](https://assets.leetcode.com/users/planegoose/image_1562855281.png)\nThen we can use bottom-up DP to solve every diagonal line,and finally get res[1][n].\n\n**Supplement**\n(res begins at 0,ends at n,just for readability.Of course it will occupy less space if we let it end at n-1.)\n(There are many vacant grid occupied(colored in gray) at left-bottom.Maybe we can improve the algorithms in this term.)\n(My code is somewhat too long,though excelling 98% in time and 97% in space,but I haven\'t compacted it,so I feel shamed to put it up.)\n\n
12
0
['Dynamic Programming']
0
unique-binary-search-trees-ii
JavaScript DFS with Memo
javascript-dfs-with-memo-by-linfongi-2twb
js\nfunction generateTrees(n) {\n if (n < 1) return [];\n const dp = [...Array(n+1)].map(r => Array(n+1));\n return generate(1, n);\n \n function generate(
linfongi
NORMAL
2018-07-19T03:11:20.463064+00:00
2018-07-19T03:11:20.463064+00:00
1,091
false
```js\nfunction generateTrees(n) {\n if (n < 1) return [];\n const dp = [...Array(n+1)].map(r => Array(n+1));\n return generate(1, n);\n \n function generate(s, e) {\n if (s > e) return [null];\n if (dp[s][e]) return dp[s][e];\n \n const res = [];\n for (let root = s; root <= e; root++) {\n for (let left of generate(s, root-1)) {\n for (let right of generate(root+1, e)) {\n const newTree = new TreeNode(root);\n newTree.left = left;\n newTree.right = right;\n res.push(newTree);\n }\n }\n }\n \n dp[s][e] = res;\n return res;\n }\n}\n```
12
0
[]
2
unique-binary-search-trees-ii
A simple bottom-up DP solution
a-simple-bottom-up-dp-solution-by-albja1-epj3
The optimal substructure is that for any BST with nodes 1 to n, pick i-th node as root, then the left subtree will contain nodes from 1 to (i-1), and the right
albja16
NORMAL
2015-04-09T10:01:27+00:00
2015-04-09T10:01:27+00:00
3,881
false
The optimal substructure is that for any BST with nodes 1 to n, pick i-th node as root, then the left subtree will contain nodes from 1 to (i-1), and the right subtree will contain nodes from (i+1) to n. I use a 3-d vector to store all possible trees for subtrees with nodes from i to j (0 <= i <= j <=n+1 ), if i==j, there is only one-node tree; if j = i-1, then there is no actual node(storing NULL pointer). Use a bottom up solution to generate all possible subtrees with nodes i to j. Finally the result will be the subtree set with nodes 1 to n, \n \n \tvector<TreeNode *> generateTrees(int n) {\n\t\tif(n == 0)\treturn vector<TreeNode *>(1, NULL);\n\t\tvector<vector<vector<TreeNode*>>> subtree(n+2, vector<vector<TreeNode*>>(n+2, vector<TreeNode*>()));\n\t\tfor(int i=1; i<=n+1; ++i){\n\t\t\tsubtree[i][i].push_back(new TreeNode(i));\n\t\t subtree[i][i-1].push_back(NULL);\t\n\t\t}\n\t\tfor(int l=2; l<=n; ++l){\n\t\t\tfor(int i=1; i<=n-l+1; ++i){\n\t\t\t\tfor(int j=i; j<=i+l-1; ++j){\n\t\t\t\t\tfor(int k=0; k<subtree[j+1][i+l-1].size(); ++k){\n\t\t\t\t\t for(int m=0; m<subtree[i][j-1].size(); ++m){\n\t\t\t\t\t TreeNode *T = new TreeNode(j);\n\t\t\t\t\t T->left = subtree[i][j-1][m];\n\t\t\t\t\t T->right = subtree[j+1][i+l-1][k];\n\t\t\t\t subtree[i][i+l-1].push_back(T); \n\t\t\t\t\t }\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn subtree[1][n];\n\t}
12
0
['Binary Search', 'Tree', 'C++']
1
unique-binary-search-trees-ii
Easy to Understand || DP solution || Iterative || Space Optimised || Better Runtime
easy-to-understand-dp-solution-iterative-zd22
\nclass Solution {\npublic:\n \n TreeNode* newTreeRight(TreeNode* root, int j){\n if(root==NULL){\n return root;\n }\n Tre
arunit
NORMAL
2022-01-06T06:32:25.911780+00:00
2022-01-06T06:32:52.695109+00:00
497
false
```\nclass Solution {\npublic:\n \n TreeNode* newTreeRight(TreeNode* root, int j){\n if(root==NULL){\n return root;\n }\n TreeNode* newRoot = new TreeNode(root->val + j);\n newRoot->left = newTreeRight(root->left, j);\n newRoot->right = newTreeRight(root->right, j);\n return newRoot;\n }\n \n vector<TreeNode*> generateTrees(int n) {\n if(n==1){\n return {new TreeNode(1)};\n }\n vector<vector<TreeNode*>> dp(n+1);\n TreeNode* root = new TreeNode(1);\n dp[1].push_back(root);\n for(int i = 2; i<=n; i++){\n for(int j = 1; j<=i; j++){\n int left = j-1;\n int right = i-j;\n if(left==0){\n for(int k = 0; k<dp[right].size(); k++){\n root = new TreeNode(j);\n TreeNode *newRoot = newTreeRight(dp[right][k], j);\n root->right = newRoot;\n dp[i].push_back(root);\n }\n }else if(right==0){\n for(int k = 0; k<dp[left].size(); k++){\n root = new TreeNode(j);\n root->left = dp[left][k];\n dp[i].push_back(root);\n }\n }else{\n for(int k = 0; k<dp[left].size(); k++){\n for(int l = 0; l<dp[right].size(); l++){\n root = new TreeNode(j);\n root->left = dp[left][k];\n TreeNode *newRoot = newTreeRight(dp[right][l], j);\n root->right = newRoot;\n dp[i].push_back(root);\n }\n }\n }\n }\n }\n return dp[n];\n }\n};\n```
11
0
['Dynamic Programming', 'C']
2
unique-binary-search-trees-ii
Unique Binary Search Trees II [C++]
unique-binary-search-trees-ii-c-by-movee-wia8
IntuitionThe task is to generate all unique binary search trees (BSTs) that can be formed with values from 1 to n. The key observation is that for each number i
moveeeax
NORMAL
2025-01-24T12:58:32.762451+00:00
2025-01-24T12:58:32.762451+00:00
980
false
# Intuition The task is to generate all unique binary search trees (BSTs) that can be formed with values from 1 to `n`. The key observation is that for each number `i` from `1` to `n`, we can consider `i` as the root of the tree. Once the root is fixed, the problem boils down to constructing the left and right subtrees, where the left subtree consists of nodes with values less than `i`, and the right subtree consists of nodes with values greater than `i`. This gives us a recursive structure where the number of unique trees formed is based on all combinations of left and right subtrees. # Approach 1. **Base Case**: If `start > end`, then there's no tree to construct, so we return a vector containing `NULL` to represent an empty subtree. 2. **Recursive Case**: For each number `i` in the range `[start, end]`, we consider it as the root of a potential tree. The left child will be a BST formed from the range `[start, i-1]`, and the right child will be a BST formed from the range `[i+1, end]`. We recursively generate all left and right subtrees, and for each combination of left and right subtrees, we create a new tree with `i` as the root. 3. **Recursive Tree Construction**: After generating all combinations of left and right subtrees, we append each resulting tree to the final list. # Complexity - **Time Complexity**: The time complexity of this solution is \(O(4^n / \sqrt{n})\), which comes from the Catalan number formula for the number of unique BSTs that can be formed. In practice, the recursive approach explores all possible combinations of left and right subtrees. - **Space Complexity**: The space complexity is \(O(4^n / \sqrt{n})\) due to the recursive stack and the storage required for the generated trees. Each unique tree takes space proportional to the number of nodes. # Code ```cpp class Solution { public: vector<TreeNode*> generateTrees(int n) { if (n == 0) return {}; return generateTrees(1, n); } vector<TreeNode*> generateTrees(int start, int end) { vector<TreeNode*> trees; if (start > end) { trees.push_back(NULL); return trees; } for (int i = start; i <= end; ++i) { vector<TreeNode*> leftSubtrees = generateTrees(start, i - 1); vector<TreeNode*> rightSubtrees = generateTrees(i + 1, end); for (TreeNode* left : leftSubtrees) { for (TreeNode* right : rightSubtrees) { TreeNode* root = new TreeNode(i); root->left = left; root->right = right; trees.push_back(root); } } } return trees; } }; ```
10
1
['C++']
0
unique-binary-search-trees-ii
java easy solution (recursion)
java-easy-solution-recursion-by-rmanish0-ta0h
\n\nclass Solution {\n public List<TreeNode> generateTrees(int n) {\n return recursion(1,n);\n }\n List<TreeNode> recursion(int start ,int end)\
rmanish0308
NORMAL
2021-07-07T05:25:43.698401+00:00
2021-07-07T05:25:43.698449+00:00
789
false
```\n\nclass Solution {\n public List<TreeNode> generateTrees(int n) {\n return recursion(1,n);\n }\n List<TreeNode> recursion(int start ,int end)\n {\n List<TreeNode> list = new ArrayList<>();\n if(start > end)\n {\n list.add(null);\n return list;\n }\n if(start == end)\n {\n list.add(new TreeNode(start));\n return list;\n }\n List<TreeNode> left,right;\n for(int i = start;i<=end;i++)\n {\n left = recursion(start,i-1);\n right = recursion(i+1,end);\n for(TreeNode lst : left)\n {\n for(TreeNode rst : right)\n {\n TreeNode root = new TreeNode(i);\n root.left = lst;\n root.right = rst;\n list.add(root);\n }\n }\n }\n return list;\n }\n}\n```\nPlease upvote if u find my code easy to understand
10
0
['Recursion', 'Java']
1
unique-binary-search-trees-ii
Easy Java solution | Faster than 96 %
easy-java-solution-faster-than-96-by-jyo-dgbw
\nclass Solution {\n public List<TreeNode> generateTrees(int n) {\n if(n < 1)return Collections.EMPTY_LIST;\n return helper(1,n);\n }\n \
jyotiprakashrout434
NORMAL
2020-07-11T18:15:46.155141+00:00
2020-07-11T18:15:46.155218+00:00
958
false
```\nclass Solution {\n public List<TreeNode> generateTrees(int n) {\n if(n < 1)return Collections.EMPTY_LIST;\n return helper(1,n);\n }\n \n private List<TreeNode> helper(int start , int end){\n List<TreeNode> ans = new ArrayList<>();\n if(start > end){\n ans.add(null);\n return ans;\n }\n \n for(int i = start ; i <= end ;i++ ){\n List<TreeNode> left = helper(start , i - 1);\n List<TreeNode> right = helper(i + 1 , end);\n \n for(TreeNode l : left){\n for(TreeNode r : right){\n TreeNode root = new TreeNode(i);\n root.left = l;\n root.right = r;\n ans.add(root);\n }\n }\n \n }\n return ans; \n }\n}\n```
10
2
['Recursion', 'Java']
3
unique-binary-search-trees-ii
[C++] Pure Recursion to DP (only with addition of 2 Lines)
c-pure-recursion-to-dp-only-with-additio-5867
There is a significant amount of improvement in the 2nd solution compared to the effort made to code that one over the inital recursive un-memoized solution.\n\
Rxnjeet
NORMAL
2022-07-14T07:47:03.200756+00:00
2022-07-19T06:29:31.895205+00:00
868
false
There is a significant amount of improvement in the 2nd solution compared to the effort made to code that one over the inital recursive un-memoized solution.\n\n# 1. Pure Recursion (43 ms)\n```\nclass Solution {\npublic:\n vector<TreeNode*> buildTrees(int l, int r) {\n \n if(l > r) return {nullptr};\n \n vector<TreeNode*> ans;\n \n for(int i=l; i<=r; ++i)\n {\n\t\t\t// set of BST\'s we can make using values [l, i-1] \n\t\t\t\n vector<TreeNode*> left = buildTrees(l, i-1);\n \n\t\t\t// set of BST\'s we can make using values [i+1, r]\n\t\t\t\n vector<TreeNode*> right = buildTrees(i+1, r);\n \n\t\t\t// creating all the possible different combinations using left and right vectors\n\t\t\t\n for(int j=0; j<left.size(); ++j)\n {\n for(int k=0; k<right.size(); ++k)\n {\n ans.push_back(new TreeNode(i, left[j], right[k]));\n }\n }\n }\n \n return ans;\n }\n vector<TreeNode*> generateTrees(int n) {\n return buildTrees(1, n);\n }\n};\n```\n\n# 2. Top-Down DP (11 ms)\n```\nclass Solution {\npublic:\n map<pair<int,int>, vector<TreeNode*>> m; //Line #1\n \n vector<TreeNode*> buildTrees(int l, int r) {\n \n if(l > r) return {nullptr};\n \n if(m.find({l, r}) != m.end()) return m[{l, r}]; //Line #2\n \n vector<TreeNode*> ans;\n \n for(int i=l; i<=r; ++i)\n {\n vector<TreeNode*> left = buildTrees(l, i-1);\n \n vector<TreeNode*> right = buildTrees(i+1, r);\n \n for(int j=0; j<left.size(); ++j)\n {\n for(int k=0; k<right.size(); ++k)\n {\n ans.push_back(new TreeNode(i, left[j], right[k]));\n }\n }\n }\n \n return m[{l, r}] = ans; //Line #3\n }\n vector<TreeNode*> generateTrees(int n) {\n return buildTrees(1, n);\n }\n};\n```
9
0
['Dynamic Programming', 'Recursion', 'Memoization', 'C', 'C++']
0
unique-binary-search-trees-ii
Recursive C++ solution : faster than 97% c++ submissions
recursive-c-solution-faster-than-97-c-su-24n2
INTUTION:\nFor every element in range 1 to n lets say (temp), we try to find its corresponding left and right subtrees by helper(start,i-1) && helper(i+1,end) i
Sanath404
NORMAL
2021-07-14T13:09:10.312598+00:00
2021-07-14T13:09:10.312636+00:00
882
false
**INTUTION:**\nFor every element in range 1 to n lets say (temp), we try to find its corresponding left and right subtrees by helper(start,i-1) && helper(i+1,end) iterate through all possibilities of them and set temp\'s left and right sub trees and push back to some vector and return.\n```\nvector<TreeNode*> generateTrees(int n) \n {\n return helper(1,n);\n }\n \n vector<TreeNode*> helper(int start,int end)\n {\n vector<TreeNode*> ans;\n if(start>end)\n {\n ans.push_back(NULL);\n return ans;\n }\n \n for(int i=start;i<=end;i++)\n {\n vector<TreeNode*> left = helper(start,i-1);\n vector<TreeNode*> right = helper(i+1,end);\n \n for(int j=0;j<left.size();j++)\n {\n for(int k=0;k<right.size();k++)\n {\n TreeNode* root = new TreeNode(i);\n root->left=left[j];\n root->right=right[k];\n ans.push_back(root);\n }\n }\n }\n return ans;\n }
9
0
['Recursion', 'C']
1
unique-binary-search-trees-ii
Approach+code
approachcode-by-geeks_12-4m2r
Honestly I was not able to solve the problem in one go. I was able to get the idea to solve the problem but wasn\'t able to implement it. \nFirstly try to solve
geeks_12
NORMAL
2021-04-23T06:33:58.903706+00:00
2021-04-23T06:33:58.903731+00:00
241
false
Honestly I was not able to solve the problem in one go. I was able to get the idea to solve the problem but wasn\'t able to implement it. \nFirstly try to solve the problem Unique Binary Search Tree\nSo here is my approach:\n1) We need to generate a ***BST*** which means that left child will contain the node value lesser than root and right child will contain the value greater than the value of root.\n2) And also I have ***n*** number of choices for the root node. \n3) So i will iterate from ***1 to n*** and will generate left and rightsubtree recursivly.\n4) Then create a tree from all the possible left and right subtree an then finally add to the solution list.\n5) Also do not forget to add the base condition.\nBase condition will be when my ***start>end***\nSo here is my code:\n```\n vector<TreeNode*> generate(int start,int end)\n { vector<TreeNode*>list;\n if(start>end)\n {\n list.push_back(nullptr);\n return list;\n }\n for(int i=start;i<=end;i++)\n {\n vector<TreeNode*>leftsubtree=generate(start,i-1);\n vector<TreeNode*>rightsubtree=generate(i+1,end);\n for(int j=0;j<leftsubtree.size();j++)\n {\n TreeNode* left=leftsubtree[j];\n for(int k=0;k<rightsubtree.size();k++)\n {\n TreeNode* right=rightsubtree[k];\n TreeNode* node=new TreeNode(i);\n node->left=left;\n node->right=right;\n list.push_back(node);\n }\n }\n \n \n }\n return list;\n }\n vector<TreeNode*> generateTrees(int n) {\n // binary search tree left node contain ->(1,i-1)and right child contain (i+1,n)\n vector<TreeNode*>ans=generate(1,n); \n return ans;\n }\n\t//HappyCoding\n\t//Stay Safe and healthy\n\t//Also if you like the post do upvote and comment
9
0
[]
2
unique-binary-search-trees-ii
JavaScript Solution - Top Down & Bottom Up Approach
javascript-solution-top-down-bottom-up-a-fbf6
Top-Down Approach:\n\n\nvar generateTrees = function(n) {\n if (n == 0) return [];\n \n return findAllUniqueTrees(1, n);\n\n function findAllUniqueT
Deadication
NORMAL
2020-06-15T17:34:47.550928+00:00
2020-06-23T23:11:05.380129+00:00
1,336
false
**Top-Down Approach:**\n\n```\nvar generateTrees = function(n) {\n if (n == 0) return [];\n \n return findAllUniqueTrees(1, n);\n\n function findAllUniqueTrees(start, end) {\n const ans = [];\n \n // base case\n if (start > end) {\n ans.push(null);\n return ans;\n };\n \n if (start == end) {\n ans.push(new TreeNode(start));\n return ans;\n }\n \n for (let i = start; i <= end; i++) {\n const leftSubTrees = findAllUniqueTrees(start, i - 1);\n const rightSubTrees = findAllUniqueTrees(i + 1, end);\n \n for (const leftSubTree of leftSubTrees) {\n for (const rightSubTree of rightSubTrees) {\n const root = new TreeNode(i);\n root.left = leftSubTree;\n root.right = rightSubTree;\n ans.push(root);\n }\n }\n }\n \n return ans;\n }\n};\n```\n\n<br>\n\n---\n\n<br>\n\n**Bottom-Up Approach:**\n\nI did not implement a clone/copy function for the subtrees. Instead, I connected multiple roots to each subtrees. I know this might not be ideal, but it seem to be an acceptable approach from observing solutions to other similar questions.\n\nFew personal comments about this problem. There were parts of it that I found difficult which generally transfer over to dynamic programming problems. One was keeping track of the off-by-one issues involving the index of the dp grid vs. the actual number used for root. Also, prior to this problem, I did not quite grasp the relationship amongst the indexes of the 3 nested for-loops. Although not completely, but I felt that this problem gave me a better understanding of them and was definitely was a good practice. Second, thanks to [@zmj97](https://leetcode.com/problems/unique-binary-search-trees-ii/discuss/671388/javascript-dp-solution) providing the idea of what to do when there is no left or right subtree. Like many people, dynamic programming is a problem that I have found difficult to master. However, recently I have committed myself to improving that weakness and hopefully will get better in due time. If anybody has any questions or constructive criticism of ways of improving my solution or approaches to dynamic programming in general, please feel free to leave your comments below. Thank you.\n\n<br>\n\n```\nvar generateTrees = function(n) {\n if (n === 0) return [];\n\n var dp = [];\n \n for (var i = 0; i < n; i++) {\n dp[i] = [];\n for (var j = 0; j < n; j++) {\n dp[i][j] = [];\n }\n }\n\n for (var len = 2; len <= n; len++) {\n for (var start = 1; start <= n - len + 1; start++) {\n const end = start + len - 1;\n for (let mid = start; mid <= end; mid++) {\n const leftSubTrees = mid - 1 - 1 < 0 ? [] : dp[start - 1][mid - 1 - 1];\n const rightSubTrees = mid + 1 - 1 >= n ? [] : dp[mid + 1 - 1][end - 1];\n \n if (leftSubTrees.length == 0) leftSubTrees.push(null);\n if (rightSubTrees.length == 0) rightSubTrees.push(null);\n \n for (const leftSubTree of leftSubTrees) {\n for (const rightSubTree of rightSubTrees) {\n const root = new TreeNode(mid);\n root.left = leftSubTree;\n root.right = rightSubTree;\n dp[start - 1][end - 1].push(root);\n }\n }\n }\n }\n \n }\n\n return dp[0][n - 1];\n};\n```
9
0
['Dynamic Programming', 'JavaScript']
1
unique-binary-search-trees-ii
Python solution
python-solution-by-zitaowang-gkcx
\nclass Solution(object):\n def generateTrees(self, n):\n """\n :type n: int\n :rtype: List[TreeNode]\n """\n def generate
zitaowang
NORMAL
2018-08-30T09:04:54.958421+00:00
2018-10-15T00:19:53.781156+00:00
1,461
false
```\nclass Solution(object):\n def generateTrees(self, n):\n """\n :type n: int\n :rtype: List[TreeNode]\n """\n def generate(i,j):\n if j-i < 0:\n return [None]\n elif j-i == 0:\n return [TreeNode(i)]\n else:\n res = []\n for k in range(i,j+1):\n left = generate(i,k-1)\n right = generate(k+1,j)\n for l in left:\n for r in right:\n root = TreeNode(k)\n root.left = l\n root.right = r\n res.append(root)\n return res\n if n == 0:\n return []\n else:\n return generate(1,n)\n```
9
0
[]
3
unique-binary-search-trees-ii
Help simplify my code (the second one)
help-simplify-my-code-the-second-one-by-6twsr
class Solution {\n private:\n \tvector<TreeNode*> generateTreesRec(int start, int end){\n \t\tvector<TreeNode*> v;\n \t\tif(start > end){\n \t\t\
lzl124631x
NORMAL
2014-03-09T12:02:23+00:00
2014-03-09T12:02:23+00:00
4,705
false
class Solution {\n private:\n \tvector<TreeNode*> generateTreesRec(int start, int end){\n \t\tvector<TreeNode*> v;\n \t\tif(start > end){\n \t\t\tv.push_back(NULL);\n \t\t\treturn v;\n \t\t}\n \t\tfor(int i = start; i <= end; ++i){\n \t\t\tvector<TreeNode*> left = generateTreesRec(start, i - 1);\n \t\t\tvector<TreeNode*> right = generateTreesRec(i + 1, end);\n \t\t\tTreeNode *node;\n \t\t\tfor(int j = 0; j < left.size(); ++j){\n \t\t\t\tfor(int k = 0; k < right.size(); ++k){\n \t\t\t\t\tnode = new TreeNode(i);\n \t\t\t\t\tnode->left = left[j];\n \t\t\t\t\tnode->right = right[k];\n \t\t\t\t\tv.push_back(node);\n \t\t\t\t}\n \t\t\t}\n \t\t}\n \t\treturn v;\n \t}\n public:\n vector<TreeNode *> generateTrees(int n) {\n return generateTreesRec(1, n);\n }\n };\n\nI think one defect of the above code is that it constructs trees interleaving with rather than being independent of each other. For example, if `n == 5` and `3` is selected as root, you'll get four trees as follow:\n\n<a href="http://www.freeimagehosting.net/xepj1"><img src="http://www.freeimagehosting.net/t/xepj1.jpg"></a>\n\nI prefer to construct independent trees so I write the following code...\n\n class Solution {\n private:\n \tTreeNode *constructBSTRec(const string &preorder, int ps, int pe, int is, int ie){\n \t\tif(ps > pe || is > ie || pe - ps != ie - is) return NULL;\n \t\tTreeNode *root = new TreeNode(preorder[ps] - '0');\n \t\tint i = preorder[ps] - '0' - 1;\n \t\tint leftLen = i - is;\n \t\troot->left = constructBSTRec(preorder, ps + 1, ps + leftLen, is, i - 1);\n \t\troot->right = constructBSTRec(preorder, ps + leftLen + 1, pe, i + 1, ie);\n \t\treturn root;\n \t}\n \tTreeNode *constructBST(const string &preorder){\n \t\treturn constructBSTRec(preorder, 0, preorder.size() - 1, 0, preorder.size() - 1);\n \t}\n \tvector<string> combine(vector<string> &s1, vector<string> &s2){\n \t\tif(s1.empty() || s2.empty()){\n \t\t\treturn s1.empty() ? s2 : s1;\n \t\t}\n \t\tvector<string> v;\n \t\tfor(int i = 0; i < s1.size(); ++i){\n \t\t\tfor(int j = 0; j < s2.size(); ++j){\n \t\t\t\tv.push_back(s1[i] + s2[j]);\n \t\t\t}\n \t\t}\n \t\treturn v;\n \t}\n \tvector<string> preorderSequence(int start, int end){\n \t\tvector<string> v;\n \t\tfor(int i = start; i <= end; ++i){\n \t\t\tvector<string> tmp;\n \t\t\ttmp.push_back(string(1, i + '0'));\n \t\t\tvector<string> left = preorderSequence(start, i - 1);\n \t\t\tvector<string> right = preorderSequence(i + 1, end);\n \t\t\ttmp = combine(tmp, left);\n \t\t\ttmp = combine(tmp, right);\n \t\t\tfor(int i = 0; i < tmp.size(); ++i){\n \t\t\t\tv.push_back(tmp[i]);\n \t\t\t}\n \t\t}\n \t\treturn v;\n \t}\n public:\n vector<TreeNode *> generateTrees(int n) {\n \tvector<TreeNode*> trees;\n \tif(n < 0) return trees;\n \tif(n == 0){\n \t\ttrees.push_back(NULL);\n \t\treturn trees;\n \t}\n \tvector<string> v = preorderSequence(1, n);\n \tfor(int i = 0; i < v.size(); ++i){\n \t\ttrees.push_back(constructBST(v[i]));\n \t}\n \treturn trees;\n }\n };\n\nThe main idea is to generate preorder sequences of unique BSTs and construct independent BSTs in the end. But I am afraid it's lack of readability. Can you help me simplify it? Any advice?\n\n\n [1]: http://www.freeimagehosting.net/xepj1
9
0
[]
7
unique-binary-search-trees-ii
DP solution in Python
dp-solution-in-python-by-heliu023-uhla
----------\n\nclass Solution:\n # @return a list of tree node\n\n def generateTrees(self, n):\n if n == 0:\n return [None]\n tree
heliu023
NORMAL
2015-03-26T22:41:17+00:00
2018-10-09T21:10:33.024397+00:00
2,524
false
----------\n\nclass Solution:\n # @return a list of tree node\n\n def generateTrees(self, n):\n if n == 0:\n return [None]\n tree_list = [[[None]] * (n + 2) for i in range(n + 2)]\n for i in range(1, n + 1):\n tree_list[i][i] = [TreeNode(i)]\n for j in reversed(range(1, i)):\n tree_list[j][i] = []\n for k in range(j, i + 1):\n for left in tree_list[j][k - 1]:\n for right in tree_list[k + 1][i]:\n root = TreeNode(k)\n (root.left, root.right) = (left, right)\n tree_list[j][i].append(root)\n return tree_list[1][n]
9
0
[]
1
unique-binary-search-trees-ii
94.15% Unique Binary Search Trees II with step by step explanation
9415-unique-binary-search-trees-ii-with-x8tc7
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\nTo generate all structurally unique BST\'s with n nodes, we can use a rec
Marlen09
NORMAL
2023-02-15T05:27:56.554445+00:00
2023-02-15T05:27:56.554485+00:00
3,523
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nTo generate all structurally unique BST\'s with n nodes, we can use a recursive approach. The idea is to fix each number i (1 <= i <= n) as the root of the tree and then recursively generate all the left and right subtrees that can be formed using the remaining numbers (1, 2, ..., i-1) and (i+1, i+2, ..., n) respectively.\n\nFor example, to generate all the BST\'s with 3 nodes, we can fix 1 as the root and recursively generate all the BST\'s with 0 and 2 nodes respectively. Then we can fix 2 as the root and recursively generate all the BST\'s with 1 node on the left and 1 node on the right. Finally, we can fix 3 as the root and recursively generate all the BST\'s with 2 and 0 nodes respectively.\n\nTo avoid generating duplicate trees, we can use memoization to store the trees generated for each combination of left and right subtree sizes.\n\n# Complexity\n- Time complexity:\nBeats\n89.57%\n\n- Space complexity:\nBeats\n94.15%\n\n# Code\n```\nclass TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\nclass Solution:\n def generateTrees(self, n: \'int\') -> \'List[TreeNode]\':\n memo = {}\n \n def generate_trees_helper(start: int, end: int) -> List[TreeNode]:\n if start > end:\n return [None]\n \n if (start, end) in memo:\n return memo[(start, end)]\n \n result = []\n \n for i in range(start, end+1):\n left_subtrees = generate_trees_helper(start, i-1)\n right_subtrees = generate_trees_helper(i+1, end)\n \n for left in left_subtrees:\n for right in right_subtrees:\n root = TreeNode(i)\n root.left = left\n root.right = right\n result.append(root)\n \n memo[(start, end)] = result\n \n return result\n \n return generate_trees_helper(1, n)\n```
8
0
['Python', 'Python3']
3
unique-binary-search-trees-ii
DP solution in C++ and Java
dp-solution-in-c-and-java-by-savan07-ahh3
Code in C++\n\nclass Solution {\npublic:\n vector<TreeNode*> generateTrees(int n) {\n return subTrees(1, n);\n }\nprivate:\n vector<TreeNode*> s
savan07
NORMAL
2022-06-29T08:45:04.689985+00:00
2022-06-29T08:45:04.690043+00:00
1,251
false
**Code in C++**\n```\nclass Solution {\npublic:\n vector<TreeNode*> generateTrees(int n) {\n return subTrees(1, n);\n }\nprivate:\n vector<TreeNode*> subTrees(int start, int end){\n vector<TreeNode*> res;\n if(start>end){\n res.push_back(NULL);\n return res;\n }\n for(int i=start; i<=end; i++){\n vector<TreeNode*> left = subTrees(start, i-1);\n vector<TreeNode*> right = subTrees(i+1, end);\n for(TreeNode* l: left){\n for(TreeNode* r: right){\n TreeNode* root = new TreeNode(i);\n root->left = l;\n root->right = r;\n res.push_back(root);\n }\n }\n }\n return res;\n }\n};\n```\n\n**Code in Java**\n```\nclass Solution {\n public List<TreeNode> generateTrees(int n) {\n return subTrees(1, n);\n }\n private List<TreeNode> subTrees(int start, int end){\n List<TreeNode> res = new ArrayList();\n if(start>end) {\n res.add(null);\n return res;\n }\n for(int i=start; i<=end; i++){\n List<TreeNode> left = subTrees(start, i-1);\n List<TreeNode> right = subTrees(i+1, end);\n for(TreeNode l: left){\n for(TreeNode r: right){\n TreeNode root = new TreeNode(i);\n root.left = l;\n root.right = r;\n res.add(root);\n }\n }\n }\n return res;\n }\n \n}\n```\n**Please upvote if you found the solution helpful**\n*Feel free to ask any questions in the comment section*
8
0
['Dynamic Programming', 'C', 'C++', 'Java']
1
unique-binary-search-trees-ii
Python Recursive Explanation
python-recursive-explanation-by-wei_lun-3kvq
For every node with value val\n\t Left subtree\'s root\'s value must be in [1, val - 1]\n\n\t Right subtree\'s root\'s value must be in [val + 1, n] \n\n2. Now,
wei_lun
NORMAL
2020-07-05T04:42:45.706126+00:00
2020-07-05T04:42:59.779286+00:00
215
false
1. For every node with value `val`\n\t* **Left subtree\'s root**\'s value must be in `[1, val - 1]`\n\n\t* **Right subtree\'s root**\'s value must be in `[val + 1, n]` \n\n2. Now, what **root value** do we get to try in each recursive call? We try root values in `[start, end]`\n\n3. This means for each root, there is a combination / list of `left` and `right` sub**trees** we get to try. (This explains the 2 `for-loops` in the recursive call)\n\n4. Therefore, this is what the `build` function does.\n\n\t* Generates a **root** with `val` between `[start, end]`\n\n\t* Generates **all** possible **left** subtree roots with value between `[start, val - 1]`\n\n\t* Generates **all** possible **right** subtree roots with value between `[val + 1, end]`\n\n\t* For **every of these combinations**, it creates a brand new tree and adds it to `trees` before returning it in each recursive call\n \n<br><br>\n\n```\nclass Solution:\n \n def generateTrees(self, n: int) -> List[TreeNode]:\n \n # EDGE CASE\n if n == 0:\n return []\n \n\t\t# CALL ON BUILD() TO RETURN THE LIST OF ROOTS\n return self.build(1, n)\n \n \n def build(self, start, end):\n trees = []\n \n # CHOOSE A ROOT VALUE ANYWHERE BETWEEN [START, END]\n for val in range(start, end + 1):\n \n # ATTACH ROOT TO EVERY POSSIBLE LEFT SUBTREE\n for left in self.build(start, val - 1):\n \n # ATTACH ROOT TO EVERY POSSIBLE RIGHT SUBTREE\n for right in self.build(val + 1, end):\n \n # CREATE A TREE AND ADD IT\n trees.append(TreeNode(val, left, right))\n \n # [NONE] = THE EMPTY TREE\n return trees or [None]\n```
8
0
[]
0
unique-binary-search-trees-ii
Quite clean Java solution with explanation
quite-clean-java-solution-with-explanati-dux5
For all possible root of the trees (i.e. 1, 2, ..., n), get the list of left subtrees and list of right subtrees, recursively. Now, for every left and right sub
whitehat
NORMAL
2015-12-30T19:30:22+00:00
2015-12-30T19:30:22+00:00
1,709
false
For all possible root of the trees (i.e. 1, 2, ..., n), get the list of left subtrees and list of right subtrees, recursively. Now, for every left and right subtree combination, create a new tree and add to resultant list.\n\nHere, "start > end" becomes the base case for recursion, for which I add "null" as the only element of list, which will form the only possible left or right subtree. (To understand why this works, check with n = 1).\n\nn = 0 is handled separately, since leetcode expects an empty list, rather than a list with a null value.\n\n public class Solution {\n public List<TreeNode> generateTrees(int n) {\n if(n == 0)\n return new ArrayList<TreeNode>();\n return generateTrees(1, n);\n }\n \n List<TreeNode> generateTrees(int start, int end) {\n List<TreeNode> result = new ArrayList<TreeNode>();\n if(start > end) {\n result.add(null);\n return result;\n }\n for(int i = start; i <= end; i++) {\n List<TreeNode> leftSubTrees = generateTrees(start, i - 1);\n List<TreeNode> rightSubTrees = generateTrees(i + 1, end);\n for(TreeNode left : leftSubTrees) {\n for(TreeNode right : rightSubTrees) {\n TreeNode root = new TreeNode(i);\n root.left = left;\n root.right = right;\n result.add(root);\n }\n }\n }\n return result;\n }\n }
8
0
['Java']
0
unique-binary-search-trees-ii
🦀 Unique Binary Search Trees II - A Rusty Approach
unique-binary-search-trees-ii-a-rusty-ap-4388
Have you ever tried to generate all unique binary search trees (BSTs) with a given number of nodes? It\'s a crab-tastic challenge, but don\'t worry; Rust is her
phistellar
NORMAL
2023-08-05T01:47:42.736731+00:00
2023-08-05T02:11:57.089894+00:00
1,558
false
Have you ever tried to generate all unique binary search trees (BSTs) with a given number of nodes? It\'s a crab-tastic challenge, but don\'t worry; Rust is here to help you out!\n\n## Intuition\nImagine you have \\( n \\) distinct numbers. You can pick any number as the root of the BST. Once you pick a root, the remaining numbers are divided into two groups, forming the left and right subtrees. You can recursively build the subtrees and combine them to form all possible BSTs.\n\n## Approach\nWe use dynamic programming to efficiently construct all possible trees. We start by building trees with 1 node, then 2 nodes, up to \\( n \\) nodes. We use previously computed solutions to build trees with more nodes, making the process fast and memory-efficient.\n\n### Example Explanation\nFor \\( n = 3 \\), the output is:\n```\n[\n [1,null,2,null,3],\n [1,null,3,2],\n [2,1,3],\n [3,1,null,null,2],\n [3,2,null,1]\n]\n```\nIt means there are 5 different ways to form a BST using numbers from 1 to 3.\n\n## Complexity\n- Time complexity: $$ O\\left(\\frac{{4^n}}{{n\\sqrt{n}}}\\right) $$\n- Space complexity: $$ O\\left(\\frac{{4^n}}{{n\\sqrt{n}}}\\right) $$\n\n## Code\nThe Rust code below generates all unique BSTs for a given number of nodes, using dynamic programming.\n\n``` Rust []\nuse std::rc::Rc;\nuse std::cell::RefCell;\n\nimpl Solution {\n pub fn generate_trees(n: i32) -> Vec<Option<Rc<RefCell<TreeNode>>>> {\n if n == 0 {\n return Vec::new();\n }\n\n let mut dp = vec![Vec::new(); (n + 1) as usize];\n dp[0].push(None);\n for nodes in 1..=n {\n let mut trees_per_node = Vec::new();\n for root in 1..=nodes {\n let left_trees = &dp[(root - 1) as usize];\n let right_trees = &dp[(nodes - root) as usize];\n for left_tree in left_trees {\n for right_tree in right_trees {\n let root_node = Some(Rc::new(RefCell::new(TreeNode::new(root))));\n root_node.as_ref().unwrap().borrow_mut().left = left_tree.clone();\n root_node.as_ref().unwrap().borrow_mut().right = Solution::clone(right_tree.clone(), root);\n trees_per_node.push(root_node);\n }\n }\n }\n dp[nodes as usize] = trees_per_node;\n }\n dp[n as usize].clone()\n }\n\n fn clone(tree: Option<Rc<RefCell<TreeNode>>>, offset: i32) -> Option<Rc<RefCell<TreeNode>>> {\n tree.map(|node| {\n Rc::new(RefCell::new(TreeNode {\n val: node.borrow().val + offset,\n left: Solution::clone(node.borrow().left.clone(), offset),\n right: Solution::clone(node.borrow().right.clone(), offset),\n }))\n })\n }\n}\n```\n``` Go []\nvar generateTrees = function(n) {\n if (n === 0) return [];\n\n const dp = Array.from({ length: n + 1 }, () => []);\n dp[0].push(null);\n for (let nodes = 1; nodes <= n; nodes++) {\n for (let root = 1; root <= nodes; root++) {\n for (const left_tree of dp[root - 1]) {\n for (const right_tree of dp[nodes - root]) {\n const root_node = new TreeNode(root);\n root_node.left = left_tree;\n root_node.right = clone(right_tree, root);\n dp[nodes].push(root_node);\n }\n }\n }\n }\n return dp[n];\n};\n\nfunction clone(n, offset) {\n if (n === null) return null;\n const node = new TreeNode(n.val + offset);\n node.left = clone(n.left, offset);\n node.right = clone(n.right, offset);\n return node;\n}\n```\n``` Python []\nclass Solution:\n def generateTrees(self, n: int):\n if n == 0:\n return []\n\n dp = [[] for _ in range(n + 1)]\n dp[0].append(None)\n for nodes in range(1, n + 1):\n for root in range(1, nodes + 1):\n for left_tree in dp[root - 1]:\n for right_tree in dp[nodes - root]:\n root_node = TreeNode(root)\n root_node.left = left_tree\n root_node.right = self.clone(right_tree, root)\n dp[nodes].append(root_node)\n return dp[n]\n \n def clone(self, n: TreeNode, offset: int) -> TreeNode:\n if n:\n node = TreeNode(n.val + offset)\n node.left = self.clone(n.left, offset)\n node.right = self.clone(n.right, offset)\n return node\n return None\n```\nExplore the beauty of constructing binary trees and have fun with Rust! If you find this solution helpful, don\'t forget to upvote and share it with fellow Rustaceans. Happy coding! \uD83E\uDD80
7
0
['Dynamic Programming', 'Go', 'Python3', 'Rust']
0
unique-binary-search-trees-ii
C++ recursive Catalan number-like DP solution
c-recursive-catalan-number-like-dp-solut-mxxu
Intuition\n Describe your first thoughts on how to solve this problem. \nUse 3D array for TreeNode* as memoization. Solve it recursely with memo. Again a DP sol
anwendeng
NORMAL
2023-07-30T08:28:34.650519+00:00
2023-07-30T08:42:01.500135+00:00
664
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nUse 3D array for TreeNode* as memoization. Solve it recursely with memo. Again a DP solution is done. \n\nThis code generates all possible unique binary search trees for a given range [1, n] using dynamic programming. It uses a 3D vector \'dp\' to store computed values and avoids redundant calculations. The function \'BSTree\' recursively forms BSTs for each range [s, e], combining left and right subtrees. The \'generateTrees\' function initializes \'dp\', then calls \'BSTree\' with range [1, n] to compute all unique BSTs. The approach is efficient and relates to Catalan numbers, representing the number of BSTs that can be formed using \'n\' nodes.\n\n# Catalan numbers\nCatalan numbers can be given by a recursive way as follows\n$$ \nG(0)=1, G(n)=\\sum_{i=1}^nG(i-1)G(n-i)\n$$\nThe solution is related to this recursive recurrence.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nSimilar idea as in solving the hard question 894. All Possible Full Binary Trees.\n[Please Turn on English subtitles if neccessary]\n[https://youtu.be/AVbHDf6H_gE](https://youtu.be/AVbHDf6H_gE)\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$O(n * G(n))$\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$O(n^2 * G(n))$\n# Code\n```\n/**\n * Definition for a binary tree node.\n * struct TreeNode {\n * int val;\n * TreeNode *left;\n * TreeNode *right;\n * TreeNode() : val(0), left(nullptr), right(nullptr) {}\n * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}\n * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}\n * };\n */\nclass Solution {\npublic:\n vector<vector<vector<TreeNode*>>> dp;\n \n vector<TreeNode*> BSTree(int s, int e){\n if (s > e) return {NULL};\n if (s == e) return {new TreeNode(s)};\n \n if (dp[s][e].size()>0) return dp[s][e];\n \n vector<TreeNode*> ans;\n for (int j = s; j <= e; j++) {\n vector<TreeNode*> Left = BSTree(s, j - 1);\n vector<TreeNode*> Right = BSTree(j + 1, e);\n \n for (TreeNode* l : Left) {\n for (TreeNode* r : Right) {\n TreeNode* root = new TreeNode(j, l, r);\n ans.push_back(root);\n }\n }\n }\n return dp[s][e] = ans;\n }\n \n vector<TreeNode*> generateTrees(int n) {\n dp.assign(n+1, vector(n+1, vector<TreeNode*>()));\n return BSTree(1, n);\n }\n};\n```\n# Code with Explanation in comments\n```\n/**\n * Definition for a binary tree node.\n * struct TreeNode {\n * int val;\n * TreeNode *left;\n * TreeNode *right;\n * TreeNode() : val(0), left(nullptr), right(nullptr) {}\n * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}\n * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}\n * };\n */\n\nclass Solution {\npublic:\n vector<vector<vector<TreeNode*>>> dp; // 3D vector to store computed values for dynamic programming\n \n // Function to generate all possible unique binary search trees given a range [s, e]\n vector<TreeNode*> BSTree(int s, int e) {\n // Base cases: If the range is invalid or contains a single element, return appropriate values.\n if (s > e) return {NULL}; // A single element in the range [s, e] cannot form a tree, so return NULL.\n if (s == e) return {new TreeNode(s)}; // A single element in the range is a valid tree by itself.\n\n if (dp[s][e].size() > 0) return dp[s][e]; // If the value has already been computed, return it from the dp array.\n\n vector<TreeNode*> ans; // Vector to store all possible BSTs in the range [s, e].\n\n // Loop through each possible root node value (j) in the range [s, e]\n for (int j = s; j <= e; j++) {\n // Recursively generate all possible left subtrees (Left) from range [s, j-1]\n vector<TreeNode*> Left = BSTree(s, j - 1);\n\n // Recursively generate all possible right subtrees (Right) from range [j+1, e]\n vector<TreeNode*> Right = BSTree(j + 1, e);\n\n // Combine all possible combinations of left and right subtrees with the current root value (j)\n for (TreeNode* l : Left) {\n for (TreeNode* r : Right) {\n TreeNode* root = new TreeNode(j, l, r); // Create a new tree with root value (j), left subtree (l), and right subtree (r).\n ans.push_back(root); // Add the current tree to the result vector.\n }\n }\n }\n\n return dp[s][e] = ans; // Store the computed value in the dp array and return the result.\n }\n\n vector<TreeNode*> generateTrees(int n) {\n dp.assign(n + 1, vector(n + 1, vector<TreeNode*>())); // Initialize the dp array with dimensions (n+1) x (n+1) x unknown.\n return BSTree(1, n); // Call the helper function with the range [1, n] to generate all possible BSTs from 1 to n.\n }\n};\n\n```
7
0
['Math', 'Dynamic Programming', 'Tree', 'Depth-First Search', 'C++']
1
unique-binary-search-trees-ii
javascript 8 line solution
javascript-8-line-solution-by-liushuaima-0vyh
```js\nvar generateTrees = function(n, l = 1, r = n, res = []) {\n for(let i = l; i <= r; i++){\n for(const left of generateTrees(n, l, i - 1)){\n
liushuaimaya
NORMAL
2019-12-22T01:47:31.033351+00:00
2019-12-22T01:48:15.715758+00:00
1,149
false
```js\nvar generateTrees = function(n, l = 1, r = n, res = []) {\n for(let i = l; i <= r; i++){\n for(const left of generateTrees(n, l, i - 1)){\n for(const right of generateTrees(n, i + 1, r)){\n res.push({val: i, left, right});\n }\n }\n }\n return n ? res.length ? res : [null] : [];\n};
7
2
['JavaScript']
0
unique-binary-search-trees-ii
C++ 16ms, beats 98.1% of cpp submissions
c-16ms-beats-981-of-cpp-submissions-by-i-u5yo
\nvector<TreeNode*> genTreesUtil(int beg, int end) {\n\tif (end < beg) return { nullptr };\n\tif (end == beg) return { new TreeNode(beg) };\n\n\tvector<TreeNode
igorleet
NORMAL
2019-05-26T00:07:40.158338+00:00
2019-05-26T00:09:12.264529+00:00
913
false
```\nvector<TreeNode*> genTreesUtil(int beg, int end) {\n\tif (end < beg) return { nullptr };\n\tif (end == beg) return { new TreeNode(beg) };\n\n\tvector<TreeNode*> trees;\n\tfor (int i = beg; i <= end; ++i) {\n\n\t\tauto leftTrees = genTreesUtil(beg, i - 1);\n\t\tauto rightTrees = genTreesUtil(i + 1, end);\n\n\t\tfor (auto& l : leftTrees)\n\t\t\tfor (auto& r : rightTrees) {\n\t\t\t\tauto t = new TreeNode(i);\n\t\t\t\tt->left = l;\n\t\t\t\tt->right = r;\n\n\t\t\t\ttrees.push_back(t);\n\t\t\t}\n\t}\n\n\treturn trees;\n}\n\nvector<TreeNode*> generateTrees(int n) {\n\tif (n == 0) return {};\n\treturn genTreesUtil(1, n);\n}\n```
7
0
['Recursion', 'C++']
4
unique-binary-search-trees-ii
(Python) accepted python code
python-accepted-python-code-by-zhshuai1-y8qu
class Solution:\n # @return a list of tree node\n def generate(self,s,t):\n '''recursion with left and right branches'''\n i
zhshuai1
NORMAL
2014-09-18T14:06:07+00:00
2014-09-18T14:06:07+00:00
2,640
false
class Solution:\n # @return a list of tree node\n def generate(self,s,t):\n '''recursion with left and right branches'''\n if s>t:return [None];\n if s==t:return [TreeNode(s)];\n re=[];\n for i in range(s,t+1):\n left=self.generate(s,i-1);\n right=self.generate(i+1,t);\n for l in left:\n for r in right:\n tmp=TreeNode(i);\n tmp.left=l;\n tmp.right=r;\n re.append(tmp);\n return re;\n def generateTrees(self, n):\n return self.generate(1,n);\n\nthe code is straight forward,first generate the left tree, then generate the right tree. for each left and right tree, generate the tree with root.
7
0
['Python']
5
unique-binary-search-trees-ii
A straightforward python solution
a-straightforward-python-solution-by-kor-irwy
from itertools import product\n \n class Solution:\n # @param {integer} n\n # @return {TreeNode[]}\n def generateTrees(self, n):\n
kord
NORMAL
2015-06-13T02:50:09+00:00
2015-06-13T02:50:09+00:00
1,575
false
from itertools import product\n \n class Solution:\n # @param {integer} n\n # @return {TreeNode[]}\n def generateTrees(self, n):\n return self.BST([i+1 for i in range(n)])\n \n def BST(self, nodes):\n trees = []\n for i in range(len(nodes)):\n for leftSubTree, rightSubTree in product(self.BST(nodes[:i]), self.BST(nodes[i+1:])):\n root = TreeNode(nodes[i])\n root.left, root.right = leftSubTree, rightSubTree\n trees.append(root)\n \n return trees or [None]
7
0
[]
0
unique-binary-search-trees-ii
.:: Kotlin ::. Short straightforward explained
kotlin-short-straightforward-explained-b-qg9c
In each step of the recursion, we set a range. By exploring within this range, we can find the nodes on the left and right of the central point, which is the ro
dzmtr
NORMAL
2023-08-05T11:40:48.819187+00:00
2023-08-05T11:40:48.819212+00:00
20
false
In each step of the recursion, we set a range. By exploring within this range, we can find the nodes on the left and right of the central point, which is the root node.\n\n\n> Complexity (time & space): O(n!)\n\n\n```kotlin []\nclass Solution {\nfun generateTrees(n: Int): List<TreeNode?> {\n fun generate(min: Int, max: Int): List<TreeNode?> {\n if (min > max) return listOf(null)\n if (min == max) return listOf(TreeNode(min))\n val roots = mutableListOf<TreeNode?>()\n\n for (i in min..max) {\n for (l in generate(min, i - 1)) {\n for (r in generate(i + 1, max)) {\n roots += TreeNode(i).apply { this.left = l; this.right = r }\n }\n }\n }\n\n return roots\n }\n\n return generate(1, n)\n}\n}\n\n```\n
6
0
['Divide and Conquer', 'Kotlin']
0
unique-binary-search-trees-ii
Python Elegant & Short | Three lines | Top-Down DP | LRU cache
python-elegant-short-three-lines-top-dow-e576
Complexity\n- Time complexity: O(n!)\n- Space complexity: O(n^{3})\n\n# Code\n\nclass Solution:\n\n def generateTrees(self, n: int) -> List[Optional[TreeNode
Kyrylo-Ktl
NORMAL
2022-08-27T16:44:12.769559+00:00
2023-08-05T11:32:43.675773+00:00
1,516
false
# Complexity\n- Time complexity: $$O(n!)$$\n- Space complexity: $$O(n^{3})$$\n\n# Code\n```\nclass Solution:\n\n def generateTrees(self, n: int) -> List[Optional[TreeNode]]:\n return self.__generate(lo=1, hi=n)\n\n @classmethod\n @cache\n def __generate(cls, lo: int, hi: int) -> list:\n if lo > hi:\n return [None]\n return [\n TreeNode(root, left, right)\n for root in range(lo, hi + 1) # All possible roots for the current subarray\n for left in cls.__generate(lo, root - 1) # All possible trees to the left of the root element\n for right in cls.__generate(root + 1, hi) # All possible trees to the right of the root element\n ]\n```
6
0
['Dynamic Programming', 'Python', 'Python3']
2
unique-binary-search-trees-ii
12 ms || 97% faster cpp solution || Clean code
12-ms-97-faster-cpp-solution-clean-code-7x1my
\nclass Solution {\npublic:\n vector<TreeNode*> helper(int start, int end){\n vector<TreeNode*> ans;\n if(start > end){\n ans.push_b
user0382o
NORMAL
2021-09-30T15:05:24.209196+00:00
2021-09-30T15:05:24.209248+00:00
500
false
```\nclass Solution {\npublic:\n vector<TreeNode*> helper(int start, int end){\n vector<TreeNode*> ans;\n if(start > end){\n ans.push_back(NULL);\n return ans;\n }\n \n for(int i = start; i <= end; i++){\n auto left = helper(start, i - 1);\n auto right = helper(i + 1, end);\n \n for(auto l : left){\n for(auto r : right){\n TreeNode* root = new TreeNode(i);\n \n root->left = l;\n root->right = r;\n ans.push_back(root);\n }\n }\n }\n return ans;\n }\n vector<TreeNode*> generateTrees(int n) {\n auto h = helper(1, n);\n return h;\n }\n};\n```
6
0
['Binary Search', 'Tree', 'Recursion', 'C', 'C++']
1
unique-binary-search-trees-ii
Simple Java Solution with comments - 1 ms - recursive
simple-java-solution-with-comments-1-ms-v6atw
Algorithm:\n\n- Imagine the input as a continuous array of integers.\n- move in a sliding window fashion considering every element as possible root.\n- For ever
seekers01
NORMAL
2020-09-26T19:56:44.196138+00:00
2020-09-27T11:49:08.200157+00:00
601
false
Algorithm:\n\n- Imagine the input as a continuous array of integers.\n- move in a sliding window fashion considering every element as possible root.\n- For every element chosen as root\n\t- everything in the array on the left will form the possible left subtrees\n\t- everything in the array on the right will form the possible right subtrees\n- Use this list of generated subtrees to form the complete forest\n\n```\nclass Solution {\n \n public List<TreeNode> generateTrees(int n) {\n return treeBuilder(1, n);\n }\n \n private List<TreeNode> treeBuilder(int start, int end) {\n if(start > end) return Collections.emptyList();\n List<TreeNode> res = new ArrayList<>();\n // n == 1\n if(start == end) {\n res.add(new TreeNode(start));\n return res;\n }\n \n // n == 2\n if( start+1 == end) {\n res.add(new TreeNode(start, null, new TreeNode(start+1)));\n res.add(new TreeNode(start+1, new TreeNode(start), null));\n return res;\n }\n \n for(int i=start; i<=end; i++) {\n TreeNode newRoot = new TreeNode(i);\n List<TreeNode> left = treeBuilder(start, i-1); // build trees only using left elements\n List<TreeNode> right = treeBuilder(i+1, end); // build trees only using right elements\n \n if(left.size() == 0) { // No left subtrees possible\n for(TreeNode node : right) {\n newRoot.right = node;\n res.add(copyTree(newRoot));\n newRoot.right = null;\n }\n } else if(right.size() == 0) { // No right subtrees possible\n for(TreeNode node : left) {\n newRoot.left = node;\n res.add(copyTree(newRoot));\n newRoot.left = null;\n }\n } else {\n\t\t\t\t// For every left subtree; process every possibility of right subtree\n\t\t\t\t// This is analogous to taking a cartesian product of possibilities\n for (TreeNode node : left) {\n newRoot.left = node;\n for(TreeNode node1 : right) {\n newRoot.right = node1;\n res.add(copyTree(newRoot));\n newRoot.right = null;\n }\n newRoot.left = null;\n }\n }\n \n }\n \n return res;\n }\n \n // Helper Function to deep copy a given tree\n private TreeNode copyTree (TreeNode head) {\n if(head == null) return head;\n TreeNode temp = new TreeNode(head.val);\n temp.left = copyTree(head.left);\n temp.right = copyTree(head.right);\n return temp;\n }\n}\n```\n\n**Please Vote up, if this helped you!!**\n\nHappy Coding! :)
6
0
['Recursion', 'Binary Tree', 'Java']
1
unique-binary-search-trees-ii
[C++] Simple recursive solution [Detailed Explanation]
c-simple-recursive-solution-detailed-exp-rrse
\n/*\n 95. Unique Binary Search Trees II\n https://leetcode.com/problems/unique-binary-search-trees-ii/\n*/\n\n/**\n * Definition for a binary tree node.\
cryptx_
NORMAL
2020-03-02T10:59:31.622233+00:00
2020-03-02T10:59:31.622288+00:00
943
false
```\n/*\n 95. Unique Binary Search Trees II\n https://leetcode.com/problems/unique-binary-search-trees-ii/\n*/\n\n/**\n * Definition for a binary tree node.\n * struct TreeNode {\n * int val;\n * TreeNode *left;\n * TreeNode *right;\n * TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass Solution {\npublic:\n vector<TreeNode*> createTree(int start, int end) {\n // base case: return nullptr\n if(end < start)\n return vector<TreeNode*>{nullptr};\n\n vector<TreeNode*> ans;\n // for current interval each number is taken as root once\n for(int i = start; i <= end; i++) {\n vector<TreeNode*> left_subtree, right_subtree;\n // recurse for left and right subtrees\n left_subtree = createTree(start, i-1);\n right_subtree = createTree(i+1, end);\n \n // fixing the current root, traverse through the ]\n // different root nodes of left and right subtrees and\n // make them the child nodes one by one\n for(int j = 0; j < left_subtree.size(); j++) {\n for(int k = 0; k < right_subtree.size(); k++) {\n // create the root \n TreeNode* root = new TreeNode(i);\n root->left = left_subtree[j];\n root->right = right_subtree[k];\n ans.emplace_back(root);\n }\n }\n\n }\n\n return ans;\n }\n\n vector<TreeNode*> generateTrees(int n) {\n if(n <= 0)\n return vector<TreeNode*>{};\n return createTree(1, n);\n \n }\n};\n```
6
0
['C', 'C++']
1
unique-binary-search-trees-ii
Two Python sol. based on DP and recursion with memorization. [ With explanation ]
two-python-sol-based-on-dp-and-recursion-3wdo
Two Python sol. based on DP and recursion with memorization\n\n------------------------------------------\n\nMethod_#1: bottom-up dynamic programming\n\n\n# Def
brianchiang_tw
NORMAL
2020-01-14T12:17:19.215688+00:00
2020-05-15T06:58:31.223281+00:00
1,330
false
Two Python sol. based on DP and recursion with memorization\n\n------------------------------------------\n\nMethod_#1: bottom-up dynamic programming\n\n```\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution:\n \n \n def clone_with_offset(self, node: TreeNode, offset):\n \n if not node:\n return None\n \n else:\n \n # Clone whole tree with constant value offset\n root_node = TreeNode( node.val + offset )\n root_node.left = self.clone_with_offset( node.left, offset )\n root_node.right = self.clone_with_offset( node.right, offset )\n \n return root_node\n \n def generateTrees(self, n: int) -> List[TreeNode]:\n \n \n if n == 0:\n # Quick response for empty tree\n return []\n \n # dynamic programming table\n bst_dp_table = [ None for i in range(n+1) ]\n \n # base case: \n bst_dp_table[0] = [None]\n \n \n # bottom-up. build bst with k nodes, k from 1 to n\n for number_of_nodes in range(1, n+1):\n \n bst_dp_table[number_of_nodes] = []\n \n # for root node of bst: 1 node \n # for left-subtree of bst : (number_of_nodes_on_left) nodes \n # for right-subtrr of bst : (k-1-number_of_nodes_on_left) nodes \n for number_of_nodes_on_left in range(0, number_of_nodes):\n \n for left_subtree in bst_dp_table[number_of_nodes_on_left]:\n \n number_of_nodes_on_right = number_of_nodes-1-number_of_nodes_on_left\n \n for right_subtree in bst_dp_table[number_of_nodes_on_right]:\n \n # construct one unique bst\n root_of_bst = TreeNode( number_of_nodes_on_left+1 )\n root_of_bst.left = left_subtree\n root_of_bst.right = self.clone_with_offset(right_subtree, number_of_nodes_on_left+1)\n \n # update dynamic programming table\n bst_dp_table[number_of_nodes].append( root_of_bst )\n \n return bst_dp_table[n]\n```\n\n---------------------------------------------------------------------------------\n\nMethod_#2: top-down recursion with memorization\n\n```\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution:\n\n def __init__(self):\n \n # memorization table\n # key : (lower bound of bst, upper bound of bst)\n # value : a list of bst, all nodes\' value in range lower bound to upper bound.\n self.bst_dict = dict()\n \n def tree_factory(self, min_val, max_val):\n \n tree_list = []\n \n if min_val > max_val:\n # Invalid case\n tree_list.append( None )\n return tree_list\n \n if (min_val, max_val) in self.bst_dict:\n # speed-up by looking memorization table\n return self.bst_dict[(min_val, max_val)]\n \n \n # generate binary search trees from all possible root node value\n for root_node_value in range( min_val, max_val+1):\n \n left_sub_trees = self.tree_factory( min_val, root_node_value-1 )\n right_sub_trees = self.tree_factory( root_node_value+1, max_val )\n \n for left_subtree in left_sub_trees:\n for right_subtree in right_sub_trees:\n \n\t\t\t\t\t# construct one unique bst\n root_node = TreeNode( root_node_value )\n root_node.left = left_subtree\n root_node.right = right_subtree\n \n tree_list.append( root_node )\n \n # update memorization table\n self.bst_dict[(min_val, max_val)] = tree_list \n return tree_list\n \n \n \n \n def generateTrees(self, n: int) -> List[TreeNode]:\n if n == 0:\n # Quick response for empty tree\n return []\n else:\n return self.tree_factory( min_val = 1, max_val = n )\n \n```
6
0
['Dynamic Programming', 'Recursion', 'Memoization', 'Python']
1
unique-binary-search-trees-ii
Divide and Conquer in Java / Scala
divide-and-conquer-in-java-scala-by-grac-rb8v
Divide into subproblems\nThe root candidate can be selected from [1, N].\n\n> Recursively solve subproblems\nAfter we decide a root x, two subtrees (i.e. subpro
gracemeng
NORMAL
2018-08-26T16:52:37.882258+00:00
2018-08-29T09:15:49.075357+00:00
696
false
> **Divide into subproblems**\nThe root candidate can be selected from `[1, N]`.\n\n> **Recursively solve subproblems**\nAfter we decide a root `x`, two subtrees (i.e. subproblems) generated. One contains nodes with values with the range `[1, x - 1]`, while the other contains nodes with values within the range `[x + 1, N]`. \nWe can solve subproblems separately following the pattern described above.\nUntil there is no nodes left to set as root (detected by `start > end`), we terminate the recursion after we add `null` to the current placement.\n\n>**Conquer results of subproblems**\nCombine the results of subproblems, i.e. try all possible combinations of a node\'s left child and right child to construct subtrees from bottom to top. \n\n\n**More on Recursion**\nThe return type of `generateTreesFrom()` is `List<TreeNode>`, which indicates all roots of generated trees until now. We receive the results(`i.e. leftSub, rightSub`), construct trees by all combinations of them, and add roots to the newly created result list of the current stack frame. The pseudo-code is as below:\n```\n init curret result;\n for leftNode in leftSub {\n for rightNode in rightSub {\n create root node with value x;\n attach leftNode, rightNode to root \n add root to curret result; \n }\n }\n\t\t\treturn curret result;\n```\n****\n> Java\n```\n public List<TreeNode> generateTrees(int n) {\n if (n == 0) return new ArrayList<>();\n if (n == 1) return new ArrayList<>(Arrays.asList(new TreeNode(n)));\n \n // Map start + " " + end to list of placement.\n Map<String, List<TreeNode>> memo = new HashMap<>(); \n \n return place(1, n, memo);\n }\n \n private List<TreeNode> place(int start, int end, Map<String, List<TreeNode>> memo) {\n List<TreeNode> placement = new ArrayList<>(); // List of root of each placement.\n // Base cases.\n if (start > end) {\n placement.add(null);\n return placement;\n }\n if (start == end) {\n placement.add(new TreeNode(start));\n return placement;\n }\n \n String memoKey = start + " " + end;\n if (memo.containsKey(memoKey)) return memo.get(memoKey);\n \n for (int x = start; x <= end; x++) {\n List<TreeNode> leftPlacement = place(start, x - 1, memo);\n List<TreeNode> rightPlacement = place(x + 1, end, memo);\n TreeNode root;\n for (TreeNode leftNode: leftPlacement) {\n for (TreeNode rightNode: rightPlacement) {\n root = new TreeNode(x);\n root.left = leftNode;\n root.right = rightNode;\n placement.add(root);\n }\n }\n }\n \n memo.put(memoKey, placement);\n return placement;\n }\n```\n> Scala\n```\nimport scala.collection.mutable.{ListBuffer, HashMap}\n\nobject Solution {\n def generateTrees(n: Int): List[TreeNode] = {\n if (n < 1) List()\n else generate(1, n, new HashMap[String, List[TreeNode]]())\n }\n \n def generate(start: Int, end: Int, memo: HashMap[String, List[TreeNode]]): List[TreeNode] = {\n val memoKey = start + " " + end\n \n if (!(memo contains memoKey)) {\n val rootList = new ListBuffer[TreeNode]()\n \n if (start > end) rootList += null\n else if (start == end) rootList += new TreeNode(start)\n else {\n for (x <- start to end) {\n val leftList = generate(start, x - 1, memo)\n val rightList = generate(x + 1, end, memo)\n for (leftNode <- leftList) {\n for (rightNode <- rightList) {\n val root = new TreeNode(x)\n root.left = leftNode\n root.right = rightNode\n rootList += root\n }\n }\n }\n }\n \n memo += memoKey -> rootList.toList\n }\n \n memo.get(memoKey).get\n }\n}\n```\n\n**(\u4EBA \u2022\u0348\u1D17\u2022\u0348)** Thanks for voting!
6
0
[]
2
unique-binary-search-trees-ii
Python generator solution
python-generator-solution-by-google-ykhb
credit goes to https://leetcode.com/discuss/3440/help-simplify-my-code-the-second-one?show=4884#a4884\n\n # Definition for a binary tree node\n # class T
google
NORMAL
2015-03-19T07:41:35+00:00
2015-03-19T07:41:35+00:00
1,587
false
credit goes to https://leetcode.com/discuss/3440/help-simplify-my-code-the-second-one?show=4884#a4884\n\n # Definition for a binary tree node\n # class TreeNode:\n # def __init__(self, x):\n # self.val = x\n # self.left = None\n # self.right = None\n \n class Solution:\n # @return a list of tree node\n # 2:30\n def generateTrees(self, n):\n nodes = map(TreeNode, range(1, n+1))\n return map(copy.deepcopy, self.buildTree(nodes))\n \n def buildTree(self, nodes):\n n = len(nodes)\n if n == 0:\n yield None\n return\n \n for i in range(n):\n root = nodes[i]\n for left in self.buildTree(nodes[:i]):\n for right in self.buildTree(nodes[i+1:]):\n root.left, root.right = left, right\n yield root
6
0
['Python']
2
unique-binary-search-trees-ii
Why is the expected result "[[]]" when the return type is just a List and not List of List?
why-is-the-expected-result-when-the-retu-c9st
Hi,\n\n8/9 test cases are passed except the following edge case:-\n\nInput : 0\nOutput : [ ]\nExpected : [ [ ] ]\n\nIt seems expected output is like a List of l
whitehat
NORMAL
2015-06-26T05:45:46+00:00
2015-06-26T05:45:46+00:00
1,140
false
Hi,\n\n8/9 test cases are passed except the following edge case:-\n\nInput : 0\nOutput : [ ]\nExpected : [ [ ] ]\n\nIt seems expected output is like a List of list. Can someone clarify what is going wrong.\n\nBelow is my java code :-\n\n public class Solution {\n public List<TreeNode> generateTrees(int n) {\n if(n == 0) {\n List<TreeNode> result = new ArrayList<TreeNode>();\n return result;\n }\n \n int[] arr = new int[n];\n for(int i = 0; i < n; i++)\n arr[i] = i + 1;\n return generate(arr, 0, n - 1);\n }\n \n List<TreeNode> generate(int[] arr, int begin, int end) {\n if(begin > end)\n return null;\n List<TreeNode> result = new ArrayList<TreeNode>();\n if(begin == end) {\n result.add(new TreeNode(arr[begin]));\n return result;\n }\n \n for(int i = begin; i <= end; i++) {\n \n List<TreeNode> leftTrees = generate(arr, begin, i - 1);\n List<TreeNode> rightTrees = generate(arr, i + 1, end);\n if(leftTrees == null) {\n for(TreeNode node : rightTrees) {\n TreeNode root = new TreeNode(arr[i]);\n root.right = node;\n result.add(root);\n }\n } else if(rightTrees == null) {\n for(TreeNode node : leftTrees) {\n TreeNode root = new TreeNode(arr[i]);\n root.left = node;\n result.add(root);\n }\n } else {\n for(TreeNode left : leftTrees) {\n for(TreeNode right : rightTrees) {\n TreeNode root = new TreeNode(arr[i]);\n root.left = left;\n root.right = right;\n result.add(root);\n }\n }\n }\n }\n return result;\n }
6
0
[]
2
unique-binary-search-trees-ii
Java concise recursive solution. 3ms
java-concise-recursive-solution-3ms-by-s-pcuh
public class Solution {\n\n public List generateTrees(int n) {\n return n > 0 ? helper(1, n) : new ArrayList();\n }\n \n private List helper(
samparly
NORMAL
2016-03-29T15:20:23+00:00
2016-03-29T15:20:23+00:00
1,047
false
public class Solution {\n\n public List<TreeNode> generateTrees(int n) {\n return n > 0 ? helper(1, n) : new ArrayList<TreeNode>();\n }\n \n private List<TreeNode> helper(int from, int n) {\n\t\tList<TreeNode> trees = new ArrayList<TreeNode>();\n\t\tfor (int i = 0; i <= n - 1; ++i) {\n\t\t\t//left i, right n-1-i\n\t\t\tList<TreeNode> leftList = helper(from, i);\n\t\t\tList<TreeNode> rightList = helper(from + i + 1, n - 1 - i);\n\t\t\tfor (TreeNode left : leftList)\n\t\t\t\tfor (TreeNode right : rightList) {\n\t\t\t\t\tTreeNode root = new TreeNode(from + i);\n\t\t\t\t\troot.left = left;\n\t\t\t\t\troot.right = right;\n\t\t\t\t\ttrees.add(root);\n\t\t\t\t}\n\t\t}\n\t\tif (trees.size() == 0)\n\t\t\ttrees.add(null);\n\t\treturn trees;\n\t}\n}
6
0
['Recursion', 'Java']
1
unique-binary-search-trees-ii
Java 2ms solution beats 92%
java-2ms-solution-beats-92-by-darksidech-x63h
/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n
darksidechris
NORMAL
2016-01-22T04:46:12+00:00
2016-01-22T04:46:12+00:00
2,017
false
/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode(int x) { val = x; }\n * }\n */\n public class Solution {\n public List<TreeNode> generateTrees(int n) {\n if(n==0) return new ArrayList<TreeNode>();\n return generateTress(1, n);\n }\n \n private List<TreeNode> generateTress(int start, int end){\n if(start>end) {\n List<TreeNode> list = new ArrayList<TreeNode>();\n list.add(null);\n return list;\n }\n if(start==end) {\n List<TreeNode> list = new ArrayList<TreeNode>();\n list.add(new TreeNode(start)); return list;\n }\n List<TreeNode> roots = new ArrayList<TreeNode>();\n for(int i=start;i<=end;i++){\n List<TreeNode> leftTrees = generateTress(start, i-1);\n List<TreeNode> rightTrees = generateTress(i+1, end);\n for(int j=0;j<leftTrees.size();j++){\n for(int k=0;k<rightTrees.size();k++){\n TreeNode root = new TreeNode(i);\n root.left = leftTrees.get(j);\n root.right = rightTrees.get(k);\n roots.add(root);\n }\n }\n \n }\n return roots;\n }\n }
6
2
[]
1
unique-binary-search-trees-ii
[Unique Binary Search Trees II] [C++] - Shallow Copy & Deep Copy
unique-binary-search-trees-ii-c-shallow-yf6ru
Shallow Copy - TreeNodes are shared between trees:\n\nclass Solution {\npublic:\n vector<TreeNode*> generateTrees(int n) {\n return n == 0 ? vector<Tr
alexander
NORMAL
2017-01-02T23:43:44.381000+00:00
2017-01-02T23:43:44.381000+00:00
367
false
**Shallow Copy** - TreeNodes are shared between trees:\n```\nclass Solution {\npublic:\n vector<TreeNode*> generateTrees(int n) {\n return n == 0 ? vector<TreeNode*>() : generate(1, n);\n }\n\n vector<TreeNode*> generate(int lo, int hi) {\n vector<TreeNode*> trees;\n if (lo > hi) {\n trees.push_back(nullptr);\n return trees;\n }\n\n for (int i = lo; i <= hi; i++) {\n vector<TreeNode*> lefts = generate(lo, i - 1);\n vector<TreeNode*> rights = generate(i + 1, hi);\n for (TreeNode* left : lefts) {\n for (TreeNode* right : rights) {\n TreeNode* node = new TreeNode(i);\n node->left = left;\n node->right = right;\n trees.push_back(node);\n }\n }\n }\n \n return trees;\n }\n};\n````\n\n**Deep Copy** - All trees use its own nodes;\n***Matrix***\n```\nclass Solution {\npublic:\n vector<TreeNode*> generateTrees(int n) {\n return n == 0 ? vector<TreeNode*>() : generate(1, n);\n }\n\nprivate:\n vector<TreeNode*> generate(int lo, int hi) {\n vector<TreeNode*> trees;\n if (lo > hi) {\n trees.push_back(nullptr);\n return trees;\n }\n\n for (int k = lo; k <= hi; k++) {\n vector<vector<TreeNode*>> lefts(1, generate(lo, k - 1));\n vector<vector<TreeNode*>> rights(1, generate(k + 1, hi));\n int l = lefts[0].size(), r = rights[0].size();\n for (int i = 0; i < l; i++) {\n for (int j = 0; j < r; j++) {\n if (j >= lefts.size()) lefts.push_back(generate(lo, k - 1));\n if (i >= rights.size()) rights.push_back(generate(k + 1, hi));\n TreeNode* node = new TreeNode(k);\n node->left = lefts[j][i];\n node->right = rights[i][j];\n trees.push_back(node);\n }\n }\n }\n\n return trees;\n }\n};\n```\n\n***Clone***\n```\nclass Solution {\npublic:\n vector<TreeNode*> generateTrees(int n) {\n return n == 0 ? vector<TreeNode*>() : generate(1, n);\n }\n\n vector<TreeNode*> generate(int lo, int hi) {\n vector<TreeNode*> trees;\n if (lo > hi) {\n trees.push_back(nullptr);\n return trees;\n }\n\n for (int i = lo; i <= hi; i++) {\n // TreeNode in this vector should only be used while combining with the first TreeNode in rights, for the rest use clone;\n vector<TreeNode*> lefts = generate(lo, i - 1);\n for (TreeNode* left : lefts) {\n vector<TreeNode*> rights = generate(i + 1, hi);\n bool first = true;\n for (TreeNode* right : rights) {\n TreeNode* node = new TreeNode(i);\n node->left = first ? left : clone(left); // the first node in rights use left, other use cloned left;\n node->right = right;\n trees.push_back(node);\n first = false;\n }\n }\n }\n \n return trees;\n }\n\nprivate:\n /* Check null both at node and left,right */\n TreeNode* clone(TreeNode* node) {\n if (!node) {\n return nullptr;\n }\n TreeNode* copy = new TreeNode(node->val);\n if (node->left) {\n copy->left = clone(node->left);\n }\n if (node->right) {\n copy->right = clone(node->right);\n }\n return copy;\n }\n};\n```
6
1
[]
0
unique-binary-search-trees-ii
🔥🔥 Very Easy || Recursion + Memoization || DP || Java || 99% Faster 🔥🔥
very-easy-recursion-memoization-dp-java-3w0gi
Approach\n- Try out all ways, i.e, Recursion\n- Memoize the recursion for repeating subproblem\n\n# Code\n\nclass Solution {\n public List<TreeNode> generate
khushdev20211
NORMAL
2023-08-05T07:03:19.662491+00:00
2023-08-06T02:55:52.861347+00:00
860
false
# Approach\n- Try out all ways, i.e, Recursion\n- Memoize the recursion for repeating subproblem\n\n# Code\n```\nclass Solution {\n public List<TreeNode> generateTrees(int n) {\n List<TreeNode>[][] dp = new List[n + 1][n + 1];\n return f(1, n, dp);\n }\n private List<TreeNode> f(int low, int high, List<TreeNode>[][] dp){\n List<TreeNode> bst = new ArrayList<>();\n if (low > high){\n bst.add(null);\n return bst;\n }\n if (dp[low][high] != null)\n return dp[low][high];\n\n for (int i = low; i <= high; i++){\n List<TreeNode> leftSubTree = f(low, i - 1, dp);\n List<TreeNode> rightSubTree = f(i + 1, high, dp);\n for (TreeNode left : leftSubTree){\n for (TreeNode right : rightSubTree){\n bst.add(new TreeNode(i, left, right));\n }\n }\n }\n return dp[low][high] = bst;\n }\n}\n```
5
0
['Java']
0
unique-binary-search-trees-ii
C++ 🔥 | Detailed Explanation of the Recursive Approach
c-detailed-explanation-of-the-recursive-hqp8w
Intuition\n- The Trees can have root nodes from 1 to n\n- Left Subtree will have elements less than the root node\n- Right Subtree will have elements greater th
arsalAbbas
NORMAL
2023-08-05T05:30:50.519766+00:00
2023-08-05T16:21:20.571490+00:00
418
false
# Intuition\n- The Trees can have root nodes from 1 to n\n- Left Subtree will have elements less than the root node\n- Right Subtree will have elements greater than the root node\n- Each left and right subtree can be treated as an individual tree which can have previousRoot-1 (starting from prevousRoot-1 till the left bound) number of root nodes and n-prevRoot (starting from previousRoot+1 till right end) number of root nodes respectively \n\n# Approach\n- Base Case 1: For invalid boundary an empty tree can be created which is returned\n- Base Case 2: When there is only a single node left the left and right value will be equal the value is pushed in the result as a node an returned\n- For Every Tree/Subtree fix 1 node as the root node (i) and find all possible left and right Subtrees for that node.\n- Every left Subtree can be combined with each of the right Subtrees to give a unique tree and vice versa\n- Generate all possible combinations for the root node and push the root node in the result vector.\n\n# Code\n```\nclass Solution {\nprivate:\n vector<TreeNode*> f(int left,int right){\n\n vector<TreeNode*> res;\n\n //Base case 1:\n if(left>right){\n res.push_back(NULL);\n return res;\n }\n //Base case 2:\n if(left==right){\n TreeNode* node= new TreeNode(left);\n res.push_back(node);\n return res;\n }\n\n //Fix the root node in i\n for(int i=left; i<=right; i++){\n //The left subtree will have elements from the left bound till i-1\n vector<TreeNode*> leftSubtree=f(left,i-1);\n //The right subtree will have elements from i+1 till the right bound\n vector<TreeNode*> rightSubtree=f(i+1,right);\n //Add all possibilities of the combinations of the left subtrees and the right subtrees for the root node i\n for(int j=0; j<leftSubtree.size(); j++){\n for(int k=0; k<rightSubtree.size(); k++){\n TreeNode* node=new TreeNode(i);\n node->left=leftSubtree[j];\n node->right=rightSubtree[k];\n res.push_back(node);\n }\n }\n\n }\n return res;\n }\npublic:\n vector<TreeNode*> generateTrees(int n) {\n return f(1,n);\n }\n};\n```\n\nPlease **UPVOTE** if you understood!
5
0
['Tree', 'Binary Search Tree', 'Combinatorics', 'C++']
2
unique-binary-search-trees-ii
Easy Java Solution
easy-java-solution-by-viraj_patil_092-pvi8
Code\n\nclass Solution {\n public List<TreeNode> generateTrees(int n) {\n\n return upvote(1,n);\n }\n\n private List<TreeNode> upvote(int s, int
Viraj_Patil_092
NORMAL
2023-08-05T04:33:47.842558+00:00
2023-08-05T04:33:47.842581+00:00
555
false
# Code\n```\nclass Solution {\n public List<TreeNode> generateTrees(int n) {\n\n return upvote(1,n);\n }\n\n private List<TreeNode> upvote(int s, int e){\n List<TreeNode> ans = new ArrayList<>();\n\n if(s>e){\n ans.add(null);\n return ans;\n }\n\n for(int i = s;i <= e;i++){\n List<TreeNode> left = upvote(s, i-1);\n List<TreeNode> right = upvote(i+1, e);\n\n for(TreeNode l : left){\n for(TreeNode r : right){\n TreeNode res = new TreeNode(i,l,r);\n ans.add(res);\n }\n }\n }\n\n return ans;\n }\n}\n```
5
0
['Dynamic Programming', 'Tree', 'Binary Search Tree', 'Binary Tree', 'Java']
0
unique-binary-search-trees-ii
Java | Memoization | Beats 99% on space and time | 15 lines
java-memoization-beats-99-on-space-and-t-h609
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
judgementdey
NORMAL
2023-04-10T03:32:39.775436+00:00
2023-04-10T20:07:59.082241+00:00
1,319
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: $$O(n^2)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n^2)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n Map<Pair<Integer, Integer>, List<TreeNode>> memo = new HashMap<>();\n\n private List<TreeNode> generateTrees(int l, int r) {\n if (l > r)\n return new ArrayList<>() {{add(null);}};\n\n var list = new ArrayList<TreeNode>();\n var pair = new Pair(l, r);\n\n if (memo.containsKey(pair))\n return memo.get(pair);\n \n for (var i=l; i<=r; i++)\n for (var left : generateTrees(l, i-1))\n for (var right : generateTrees(i+1, r))\n list.add(new TreeNode(i, left, right));\n \n memo.put(pair, list);\n return list;\n }\n\n public List<TreeNode> generateTrees(int n) {\n return generateTrees(1, n);\n }\n}\n```\nIf you like my solution, please upvote it!
5
0
['Dynamic Programming', 'Binary Search Tree', 'Recursion', 'Java']
1
unique-binary-search-trees-ii
C++ Solution
c-solution-by-pranto1209-1gho
Code\n\n/**\n * Definition for a binary tree node.\n * struct TreeNode {\n * int val;\n * TreeNode *left;\n * TreeNode *right;\n * TreeNode() :
pranto1209
NORMAL
2023-01-02T13:27:46.389929+00:00
2023-03-14T08:19:40.042820+00:00
1,736
false
# Code\n```\n/**\n * Definition for a binary tree node.\n * struct TreeNode {\n * int val;\n * TreeNode *left;\n * TreeNode *right;\n * TreeNode() : val(0), left(nullptr), right(nullptr) {}\n * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}\n * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}\n * };\n */\n\nclass Solution {\npublic:\n vector<TreeNode*> solve(int start, int end) {\n vector<TreeNode*> ans;\n if(start > end) return {NULL};\n if(start == end) return {new TreeNode(start)};\n for(int i=start; i<=end; i++) {\n vector<TreeNode*> left = solve(start, i-1);\n vector<TreeNode*> right = solve(i+1, end);\n for(auto l: left)\n for(auto r: right)\n ans.push_back(new TreeNode(i, l, r));\n }\n return ans;\n }\n \n vector<TreeNode*> generateTrees(int n) {\n vector<TreeNode*> ans = solve(1, n);\n return ans;\n }\n};\n```
5
0
['C++']
0
unique-binary-search-trees-ii
Java fast clean concise memoized recursion explained - 0ms/100%
java-fast-clean-concise-memoized-recursi-znpt
Intuition We can break the problem into a subproblem by asking what are all of structures for a given root value. If we do this, then by virtue of the definiti
mattihito
NORMAL
2022-04-10T19:13:31.497352+00:00
2022-04-10T19:18:52.391503+00:00
419
false
**Intuition** We can break the problem into a subproblem by asking what are all of structures for a given root value. If we do this, then by virtue of the definition of a binary search tree, all the values less than our root value will be within a left subtree, and al the values greater than our root value will be within a right subtree. But then, we can repeat this process for both the left and right children, suggesting that recursion will be of help.\n\n**Optimization** The input limit n=8 is not very high, but if we want to squeeze every millisecond out of our solution, we should consider one more thing. We are going to run into a lot of the same small subtrees over and over. We can remember these for quick lookup instead of rebuilding them each time. This will also save some space. This combined with an array-based cache (see **Java Syntax Cleanup**) will put our solution in the fastest class of Java solutions.\n\n**Jave Syntax Cleanup** It\'s nice to use arrays for memoization because they are faster and read more cleanly. For example, `memo[1][2]` looks nicer (and is faster) than `memo.get(1).get(2)`. But when you want to create an array out of `List<TreeNode>` elements, Java makes it disgustingly hard to do this without casting, etc. But there\'s a trick - you can create a subclass such as `TreeNodeList` which extends a list of a given type (such as `ArrayList<TreeNode>`, but doesn\'t add any methods. It\'s purely an extension to specify a type parameter. Then we can create `TreeNodeList` arrays for memoization, where each `TreeNodeList` element is a `List<TreeNode>`. By having an array-based instead of list-based cache, we\'ll also jump into the top tier in terms of performance of java solutions, with runtimes of 0-1ms for the test suite.\n\n**Java Code** O(n^2) space, O(n^2) time. Space is n^2 due to memoization. Time would be 2^n except using memoization, we short curcuit frequently. If we assume that only tree-building is an operation, and a cache hit is not, then due to the size of our cache, we can do at most (n+2)(n+2) operations to fill it, which is O(n^2).\n\n```\nclass Solution {\n\n public List<TreeNode> generateTrees(int n) {\n final int limit = n + 1; // upper bound, exclusive\n TreeNodeList[][] memo = new TreeNodeList[limit + 1][limit + 1];\n return generateTrees(1, limit, memo);\n }\n\n private TreeNodeList generateTrees(int low, int limit, TreeNodeList[][] memo) {\n TreeNodeList cached = memo[low][limit];\n if (cached != null) {\n return cached;\n }\n TreeNodeList out = new TreeNodeList();\n for (int r = low; r < limit; ++r) {\n TreeNodeList leftNodes = generateTrees(low, r, memo);\n TreeNodeList rightNodes = generateTrees(r + 1, limit, memo);\n for (TreeNode left : leftNodes) {\n for (TreeNode right : rightNodes) {\n TreeNode root = new TreeNode(r);\n root.left = left;\n root.right = right;\n out.add(root);\n }\n }\n }\n // Small correction: the list of all trees we can make without any values is [null],\n\t\t// not []. That is, if we have no node values, there is one possible tree: null.\n\t\t// So we correct empty lists by making them lists of a single null element, instead.\n // This makes looping and generating left and right children more straight-forward.\n if (out.isEmpty()) {\n out.add(null);\n }\n memo[low][limit] = out;\n return out;\n }\n\n static class TreeNodeList extends ArrayList<TreeNode> {\n // This class exists simply for the convenience of creating arrays without a type parameter.\n }\n\n}\n```\n\nIf you found this explanation and thought process helpful, please consider an upvote so someone else is more likely to find it, too. And if not, I would sincerely appreciate your constructive criticism so I can learn to write better solutions. Thanks for your time, and happy problem-solving!
5
0
['Depth-First Search', 'Recursion', 'Memoization', 'Java']
0
unique-binary-search-trees-ii
C solution
c-solution-by-linhbk93-96lp
\nstruct TreeNode** creatTrees(int low, int high, int *size)\n{ \n if(low > high)\n {\n struct TreeNode ** out = (struct TreeNode **)malloc(sizeof(
linhbk93
NORMAL
2021-09-03T04:48:07.570166+00:00
2021-09-03T04:48:07.570202+00:00
428
false
```\nstruct TreeNode** creatTrees(int low, int high, int *size)\n{ \n if(low > high)\n {\n struct TreeNode ** out = (struct TreeNode **)malloc(sizeof(struct TreeNode*));\n *size = 1;\n out[0] = NULL;\n return out;\n }\n struct TreeNode ** out = (struct TreeNode **)malloc(2000*sizeof(struct TreeNode*));\n *size = 0;\n for(int i=low; i<=high; i++)\n {\n int leftSize = 0, rightSize = 0;\n struct TreeNode ** leftNodes = creatTrees(low, i-1, &leftSize);\n struct TreeNode ** rightNodes = creatTrees(i+1, high, &rightSize);\n for(int k=0; k<leftSize; k++)\n for(int j=0; j<rightSize; j++)\n {\n out[*size] = (struct TreeNode *)malloc(sizeof(struct TreeNode));\n out[*size]->val = i;\n out[*size]->left = leftNodes[k];\n out[*size]->right = rightNodes[j];\n *size += 1;\n }\n }\n return out;\n}\nstruct TreeNode** generateTrees(int n, int* returnSize){\n return creatTrees(1, n, returnSize);\n}\n```
5
0
['Recursion', 'C']
0
unique-binary-search-trees-ii
java solution explained TC : 92%, better variable naming
java-solution-explained-tc-92-better-var-7wpc
Basic Approach\nwe create another function called generateBSTs which takes two parameters, the strart node value and the end node value\n1. If the start node va
lahari_bitra
NORMAL
2021-09-02T17:27:11.660986+00:00
2021-09-03T08:51:48.414185+00:00
680
false
# Basic Approach\nwe create another function called generateBSTs which takes two parameters, the strart node value and the end node value\n1. If the start node value is greater than the end node then add the null to the currentBST list and return it\n2. for every node from start to end, make it as our root node value do\n3. call generateBSTs to generate leftSubtree with start as current start and end as value before until current root value ,which returns the list of roots of unique left subtrees formed with values from start to currentroot value - 1 \n4. call generateBSTs to generate rightSubtree with start as current currentrootvalue + 1 and end as current end ,which returns the list of roots of unique right subtrees formed with values from currentroot value + 1 to end\n5. now to get all combinations of left subtrees and right subtrees for the current root, traverse using two for loops and create a root with value as current root value and add the leftchild and rightchild with the help of for loops\n6. add the root node to the currentBST list\n7. return the currentBST list \n# Code\n```\nclass Solution {\n public List<TreeNode> generateTrees(int n) {\n return generateBSTs(1, n);\n }\n List<TreeNode> generateBSTs(int start, int end) {\n List<TreeNode> currentBSTs = new ArrayList<>();\n if(start > end) currentBSTs.add(null); \n else {\n for(int rootVal = start; rootVal <= end; rootVal ++) { \n List<TreeNode> leftSubtreeRoots = generateBSTs(start, rootVal - 1);\n List<TreeNode> rightSubtreeRoots = generateBSTs(rootVal + 1, end);\n for(TreeNode leftChild : leftSubtreeRoots) { \n for(TreeNode rightChild : rightSubtreeRoots) {\n TreeNode root = new TreeNode(rootVal);\n root.left = leftChild;\n root.right = rightChild;\n currentBSTs.add(root);\n }\n }\n }\n }\n return currentBSTs;\n }\n}\n```
5
0
['Recursion', 'Java']
1
unique-binary-search-trees-ii
Simple Solution with detailed Explanation and comments
simple-solution-with-detailed-explanatio-esed
Intuition:\nThe idea is to generate trees in inorder fashion , making each number in the range[1.n] as the root one by one and recursively obtaining its left an
priyankgarg02
NORMAL
2021-09-02T15:54:57.631740+00:00
2021-09-02T15:54:57.631768+00:00
213
false
**Intuition:**\nThe idea is to generate trees in inorder fashion , making each number in the range[1.n] as the root one by one and recursively obtaining its left and right subtrees ensuring that BST properties doesnt gets violated.\nIf the Root Value is i\n* Left subtree will contain values in range[start,i-1]\n* right subrees will contain valyes in range[i+1,end]\n\nfor a particular root value \'i\' there are many left and right subtrees possible , so generate all of them and combine all of them and appending to our final result vector of all BSTs.\n\n**Base Case:**\nThere are two base cases:\n* If start exceeds end; start>end, there is no tree possible, so instead of returning empty list (which will cause unexpected loop termination in the parent recursive call) , we will append null to the result list and return result.\n* if start=end, there is only one number in range i.e. start, so only one Tree possible rooted at start and left and right subtree as null, so, make this tree and add to result list and return.\n\nHere is my code:\n```\n\nclass Solution {\npublic:\n vector<TreeNode*> generateTrees(int n) {\n return helper(1,n);//To generate all the BST possible in range(1,n) \n }\n vector<TreeNode*> helper(int start, int end){\n vector<TreeNode*> allTrees;//vector to store all bsts\n if(start>end)//base case\n {\n allTrees.push_back(NULL); //No Tree is possible if start>end so push none and return\n return allTrees;\n }\n if(start==end) // Base case 2 \n {\n TreeNode* root=new TreeNode(start); // if there is only 1 number in range i.e. start=end then make th\n // only number as root node and return\n allTrees.push_back(root);\n return allTrees;\n \n }\n // making all numbers from start to end as root one by one and generating their left and right subtrees according to BST rules\n for(int CurRootVal=start;CurRootVal<=end;CurRootVal++)\n {\n vector<TreeNode*>allLeftSubtrees=helper(start,CurRootVal-1); // generated Leftsubtrees contains values in range[start,currootvalue-1]\n vector<TreeNode*>allRightSubtrees=helper(CurRootVal+1,end); //generated rightsubtrees contains values in range[currootvalue+1,end]\n for(auto leftsubtree : allLeftSubtrees) // traversing each of the left subtrees generated\n {\n for(auto rightsubtree : allRightSubtrees) // for each left subtree, all the right subtrees generated are traversed and combined as below \n {\n TreeNode* curRoot=new TreeNode(CurRootVal); // making root node of value curRootVal\n curRoot->left=leftsubtree; // adding leftsubtree to the left child of current root\n curRoot->right=rightsubtree;// adding right subtree to the right child of current root\n allTrees.push_back(curRoot);// appending the tree generated to the result alltrees\n }\n }\n \n }\n return allTrees;\n \n }\n};\n```\n\nComment down in case of any queries.\n\n**Please upvote if it helps you :)**
5
1
['Dynamic Programming', 'Tree', 'Recursion', 'C++']
0
unique-binary-search-trees-ii
C++ Easy to understand Recursive Approach with comments :)
c-easy-to-understand-recursive-approach-5m0mk
Hi,\n\nIf this helps please do UPVOTE or if you have any query or doubt COMMENT it down.\n\nclass Solution {\npublic:\n \n\t// function that takes sub parame
drig
NORMAL
2021-07-08T14:51:09.944875+00:00
2021-07-08T14:51:09.944920+00:00
591
false
Hi,\n\n**If this helps please do UPVOTE or if you have any query or doubt COMMENT it down.**\n```\nclass Solution {\npublic:\n \n\t// function that takes sub parameters left and right value\n vector<TreeNode*> solve(int l,int r){\n vector<TreeNode*> ans;\n \n\t\t// if l>r just return null\n if(l>r){\n ans.push_back(NULL);\n return ans;\n }\n\t\t// if l==r then we have only 1 node with value l or r\n if(l==r){\n TreeNode* temp=new TreeNode(l);\n ans.push_back(temp);\n return ans;\n }\n \n\t\t// else for every k between l to r append subtree of values left to it to left child and subtrees of values right to it to right child of k\n vector<TreeNode*> ansl; // stores pointer to left subtree\n vector<TreeNode*> ansr; // stores pointer to right subtree\n\n for(int k=l;k<=r;k++){\n ansl = solve(l,k-1);\n ansr = solve(k+1,r);\n if(ansl.size()==0) ansl.push_back(NULL);\n if(ansr.size()==0) ansr.push_back(NULL);\n\t\t\t\n\t\t\t// make all combinations with left current and right\n for(int i=0;i<ansl.size();i++){\n for(int j=0;j<ansr.size();j++){\n TreeNode* temp = new TreeNode(k,ansl[i],ansr[j]);\n ans.push_back(temp);\n }\n }\n }\n return ans;\n }\n \n \n vector<TreeNode*> generateTrees(int n) {\n \n return solve(1,n);\n \n }\n};\n```
5
1
['Tree', 'Recursion', 'C', 'C++']
1
unique-binary-search-trees-ii
C++; Simple and Elegant
c-simple-and-elegant-by-pranavkumarkunal-9c0f
Runtime: 8 ms, faster than 99.46% of C++ online submissions for Unique Binary Search Trees II.\nMemory Usage: 14 MB, less than 63.64% of C++ online submissions
pranavkumarkunal
NORMAL
2020-08-23T04:41:24.059224+00:00
2020-08-23T04:41:24.059279+00:00
393
false
**Runtime: 8 ms, faster than 99.46% of C++ online submissions for Unique Binary Search Trees II.\nMemory Usage: 14 MB, less than 63.64% of C++ online submissions for Unique Binary Search Trees II.**\n\n```\n/**\n * Definition for a binary tree node.\n * struct TreeNode {\n * int val;\n * TreeNode *left;\n * TreeNode *right;\n * TreeNode() : val(0), left(nullptr), right(nullptr) {}\n * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}\n * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}\n * };\n */\nclass Solution {\nprivate:\n vector<TreeNode *> helper(int start, int end)\n {\n if(start > end)\n return vector<TreeNode*>(1, NULL);\n if(start == end)\n return vector<TreeNode*>(1, new TreeNode(start));\n \n vector<TreeNode *> result, left, right;\n \n for(int i = start; i <= end; i++)\n {\n left = helper(start, i - 1);\n right = helper(i + 1, end);\n \n for(TreeNode *lNode: left)\n {\n for(TreeNode *rNode: right)\n result.push_back(new TreeNode(i, lNode, rNode));\n }\n }\n return result;\n }\npublic:\n vector<TreeNode*> generateTrees(int n) {\n if(n == 0)\n return vector<TreeNode*>();\n return helper(1, n);\n }\n};\n```
5
0
[]
1
unique-binary-search-trees-ii
C++ #miminalizm
c-miminalizm-by-votrubac-i1d9
cpp\nvector<TreeNode*> generateTrees(int end, int start = 0) {\n if (start > end)\n return { nullptr };\n vector<TreeNode*> res;\n for (auto i =
votrubac
NORMAL
2020-03-25T23:58:48.602040+00:00
2020-03-25T23:59:41.897541+00:00
343
false
```cpp\nvector<TreeNode*> generateTrees(int end, int start = 0) {\n if (start > end)\n return { nullptr };\n vector<TreeNode*> res;\n for (auto i = max(1, start); i <= end; ++i) {\n for (auto l : generateTrees(i - 1, max(1, start)))\n for (auto r : generateTrees(end, i + 1)) {\n res.push_back(new TreeNode(i));\n res.back()->left = l;\n res.back()->right = r;\n }\n }\n return res;\n}\n```
5
0
[]
1
unique-binary-search-trees-ii
cpp easy to understand recursive solution with explanation
cpp-easy-to-understand-recursive-solutio-x7bh
Explanation :\nEvery element in the array[1,n] can be a root sometime, because of the BST property, \nif ith element is chosen as the root, then the elements fr
fight_club
NORMAL
2019-08-04T05:10:25.962325+00:00
2019-08-04T05:11:41.508652+00:00
261
false
Explanation :\nEvery element in the array[1,n] can be a root sometime, because of the BST property, \nif ith element is chosen as the root, then the elements from [1,i-1] will form the left subtree & [i+1,n] will form the right subtree.\nWhat we ask recursion to do is , for each ith element , return all possible combinations of left subtree & right subtree, then we will attach the root(ith element) in all possible combinations.\nThat\'s it.\nkEEP it simple, keep coding :)\n```\n/**\n * Definition for a binary tree node.\n * struct TreeNode {\n * int val;\n * TreeNode *left;\n * TreeNode *right;\n * TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass Solution {\npublic:\n vector<TreeNode*> generateTrees(int n) {\n if (n==0) return {};\n return helper(1,n);\n }\n \n \n vector <TreeNode*> helper(int start, int end){\n if (start>end) return {nullptr};\n vector <TreeNode* > ans;\n for (int i=start; i <= end; ++i)\n {\n auto leftSubTree = helper(start, i-1);\n auto rightSubTree = helper(i+1,end);\n for (auto a:leftSubTree){\n for (auto b:rightSubTree){\n TreeNode *Node = new TreeNode(i); \n Node->left= a;\n Node->right= b;\n ans.push_back(Node);\n } \n }\n }\n return ans; \n } \n};\n```
5
0
[]
0
unique-binary-search-trees-ii
C++ iterative DP solution, reuse tree nodes (both 100%)
c-iterative-dp-solution-reuse-tree-nodes-5v6r
Runtime: 16 ms, faster than 100.00% of C++ online submissions for Unique Binary Search Trees II.\nMemory Usage: 11.6 MB, less than 100.00% of C++ online submiss
alreadydone
NORMAL
2019-03-27T06:37:11.849068+00:00
2019-03-27T06:37:11.850113+00:00
484
false
Runtime: 16 ms, faster than 100.00% of C++ online submissions for Unique Binary Search Trees II.\nMemory Usage: 11.6 MB, less than 100.00% of C++ online submissions for Unique Binary Search Trees II.\n\nBTW, I think {NULL} should be returned in the case n = 0, but I have to return {} to pass the test case; I think this is LC\'s mistake.\n```\nclass Solution {\npublic:\n vector<TreeNode*> generateTrees(int n) {\n if (n == 0) return {};\n vector<TreeNode*> nul = {NULL};\n vector<vector<vector<TreeNode*>>> trees(n);\n // all trees in trees[i][j] contain exactly the numbers from j+1 to j+i+1\n for (int i = 0; i < n; ++i) {\n trees[i].resize(n-i);\n for (int j = 0; j < n-i; ++j) {\n for (int k = 0; k <= i; ++k) {\n auto jk1 = j+k+1;\n auto& left = k == 0 ? nul : trees[k-1][j];\n auto& right = k == i ? nul : trees[i-k-1][jk1];\n for (auto l : left) for (auto r : right) {\n trees[i][j].emplace_back(new TreeNode(jk1));\n trees[i][j].back()->left = l;\n trees[i][j].back()->right = r;\n }\n } \n }\n }\n return trees.back()[0];\n }\n};\n```
5
0
[]
1
unique-binary-search-trees-ii
My non-recursive C++ solution
my-non-recursive-c-solution-by-roddykou-pf2s
vector<TreeNode *> generateTrees(int n) {\n vector<TreeNode *> tmp;\n vector<TreeNode *> ret;\n tmp.push_back(NULL); \n ret.p
roddykou
NORMAL
2015-04-01T05:28:48+00:00
2015-04-01T05:28:48+00:00
1,040
false
vector<TreeNode *> generateTrees(int n) {\n vector<TreeNode *> tmp;\n vector<TreeNode *> ret;\n tmp.push_back(NULL); \n ret.push_back(new TreeNode(1));\n if (!n) return tmp;\n\n\t\t/* insert the largeset number into previously contructed trees */\n for (int i = 2; i <= n; i++) {\n tmp.clear();\n for (int j = 0; j < ret.size(); j++) {\n\t\t\t\t/* firstly, put the largest number on the top of tree */\n TreeNode *orgTree = ret[j]; \n TreeNode *newNode = new TreeNode(i);\n newNode->left = copy(orgTree);\n tmp.push_back(newNode);\n \n\t\t\t\t/* traverse thru the right-most branch, \n\t\t\t\t * insert the largest number one position after another */\n TreeNode *orgRunner = orgTree;\n while (orgRunner) {\n newNode = new TreeNode(i);\n newNode->left = orgRunner->right;\n orgRunner->right = newNode;\n tmp.push_back(copy(orgTree));\n\t\t\t\t\t\n\t\t\t\t\t/* recover the original tree */\n orgRunner->right = orgRunner->right->left;\n\t\t\t\t\t\n\t\t\t\t\t/* for the next loop */\n orgRunner = orgRunner->right;\n }\n }\n ret = tmp;\n }\n return ret;\n }\n \n TreeNode *copy (TreeNode *root) {\n TreeNode *ret = NULL;\n if (root) {\n ret = new TreeNode(root->val);\n ret->left = copy(root->left);\n ret->right = copy(root->right);\n }\n return ret;\n }
5
0
[]
0
unique-binary-search-trees-ii
Possibly the worst C++ solution ever! 💣💥 | No DP | Pure Backtracking | Bruteforce of Bruteforce
possibly-the-worst-c-solution-ever-no-dp-cl54
Intuition \n\n- ###### Generate all possible permutations of numbers from 1 to n and construct a binary search tree (BST) for each permutation.\n - for exampl
quagmire8
NORMAL
2024-03-31T04:10:08.110413+00:00
2024-03-31T04:10:08.110438+00:00
41
false
# Intuition \n\n- ###### Generate all possible permutations of numbers from 1 to n and construct a binary search tree (BST) for each permutation.\n - for example we have <1,2,3>\n - All possible permutations for 1,2,3 will be :\n ```\n # In total there will be 3! factorial permuatations\n a) 1,2,3\n b) 1,3,2\n c) 2,1,3\n d) 2,3,1\n e) 3,1,2\n f) 3,2,1\n ```\n - So we will generate BSTs for all of these permutations\n- ###### We then check if each generated BST is unique by comparing it with the previously generated trees in the `Ans` vector.\n - The above step basically just means that we will have to check if the generated BSTs from permutations are all unique as we cant have duplicates\n\n- ###### If the BST is unique, we add it to our list of unique BSTs.\n---\n# Algorithm\n1. Define a class variable `Ans` to store the roots of the generated BSTs.\n2. Implement a function `isSameTree` to check if two binary trees are identical.\n3. Implement a function `insertInBST` to insert a node into a BST.\n4. Implement a function `createBST` to create a BST from a given permutation of numbers.\n5. Implement a recursive function `generatePermutations` to generate all permutations of numbers from 1 to n, create BSTs from each permutation, and add unique BSTs to `Ans`.\n6. In the `generateTrees` function, generate permutations, create BSTs, and return the list of unique BSTs.\n\n---\n# Complexity\n- Time complexity: $$O(n^3 \\cdot n!)$$, where n is the input parameter. \n - Generating permutations takes $$O(n!)$$ time, and for each permutation, creating a BST takes $$O(n^2)$$ time. Also checking if a BST is unique or not takes $$O(n)$$ time.Hence the overall TC is $$O(n^3 \\cdot n!)$$.\n- Space complexity: $$O(n \\cdot n!)$$, where n is the input parameter. The space complexity is dominated by the storage of unique BSTs.\n---\n# Code in C++\n\n```cpp\n/**\n * Definition for a binary tree node.\n * struct TreeNode {\n * int val;\n * TreeNode *left;\n * TreeNode *right;\n * TreeNode() : val(0), left(nullptr), right(nullptr) {}\n * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}\n * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}\n * };\n */\nclass Solution {\npublic:\n\n // class variable to store the root of the trees\n vector<TreeNode*> Ans;\n\n bool isSameTree(TreeNode* p, TreeNode* q){\n\n if(!p && !q) return true;\n if(!p || !q) return false;\n if(p->val != q->val) return false;\n\n return isSameTree(p->left,q->left) && isSameTree(p->right,q->right);\n }\n\n TreeNode* insertInBST(TreeNode* root, int val){\n\n if(!root){\n return new TreeNode(val);\n }\n\n if(root->val < val){\n root->right = insertInBST(root->right,val);\n }\n else{\n root->left = insertInBST(root->left,val);\n }\n\n return root;\n }\n\n // create the BST\n TreeNode* createBST(vector<int> &V){\n\n TreeNode* root = new TreeNode(V[0]);\n\n for(int i=1; i<V.size(); i++){\n insertInBST(root,V[i]);\n }\n\n return root;\n }\n\n // generate permutations\n void generatePermutations(string &input ,vector<int> &output){\n\n // base case(s)\n if(input.size() == 0){\n \n TreeNode* root = createBST(output);\n bool add = true;\n for(auto &tree : Ans){\n if(isSameTree(root,tree)){\n add = false;\n break;\n }\n }\n\n if(add){\n Ans.push_back(root);\n }\n\n return;\n }\n\n // recursive case(s)\n for(int i=0; i<input.size(); i++){\n\n output.push_back(input[i] - \'0\');\n string newIp = input.substr(0,i) + input.substr(i+1);\n\n generatePermutations(newIp,output);\n \n // backtracking step(s)\n output.pop_back();\n }\n\n }\n\n vector<TreeNode*> generateTrees(int n){\n \n // the most easiest and brute force approach that i can think of right now is that \n // first we will generate all the permutations of the number from 1 to n\n // then for each permutation we can create a bst using a our custom made function\n\n string ip = "";\n vector<int> op;\n for(int i=1; i<=n; i++) ip.push_back(i + \'0\');\n\n generatePermutations(ip,op);\n\n return Ans;\n }\n};\n```\n---\n![sanjiLC.png](https://assets.leetcode.com/users/images/d5d0e731-dd64-4c20-bc85-b73fd11fbbd3_1711857913.2355058.png)\n\n# **If you liked the solution (I know you didnt :P), Dont forget to upvote! Happy Leetcoding.**\n\n
4
0
['Backtracking', 'Tree', 'Binary Search Tree', 'Binary Tree', 'C++']
0
unique-binary-search-trees-ii
Recusive solution with and without memoization in c++ 💯💯🔥🔥✅✅
recusive-solution-with-and-without-memoi-sa9u
Intuition\n Describe your first thoughts on how to solve this problem. \n The recursive approach explores all possible combinations of left and right subtrees
pahadi_rawat
NORMAL
2024-02-14T10:06:47.163650+00:00
2024-02-14T10:07:15.032115+00:00
1,071
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n The recursive approach explores all possible combinations of left and right subtrees for each root value within the given range.\n\n The DP table is used to store and retrieve already computed results, avoiding redundant calculations and improving efficiency.\n\n The base cases handle scenarios where the range is invalid (start > end) or contains only a single element (start == end).\n\n The main function initiates the process for the entire range, and the recursive calls handle the smaller subproblems.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nHere\'s a breakdown of the approach:\n\n Recursive Function (solve): This function takes a range [start, end] and returns a vector of all possible unique BSTs that can be formed using values from the range.\n \n If start > end, it means an empty subtree, and a vector containing a single NULL element is returned.\n\nIf start == end, a single-node tree with the value start is created, and a vector containing this tree is returned.\n\nIf the result for the given range is already computed (dp.find({start, end}) != dp.end()), it is directly returned from the dynamic programming (DP) table.\n\nOtherwise, it recursively generates all possible combinations of left and right subtrees for each possible root value in the range.\n\n Main Function (generateTrees): This function initializes the process by calling the solve function for the entire range [1, n].\n\n\n Dynamic Programming Table (dp): A map is used to store the computed results for subproblems. The key is a pair representing the start and end of the range, and the value is a vector of TreeNode* representing all possible BSTs in that range.\n\n Node Creation: For each root value (i) in the range [start, end], it recursively calculates the left and right subtrees (a and b). Then, for each combination of left and right subtree, a new TreeNode is created with i as the root, and the left and right pointers are set accordingly. The resulting tree is added to the Result vector.\n\nMemoization: The computed result for the current range is stored in the DP table before returning it.\n# Complexity\n- Time complexity:\n- o(catlan number)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n for dp map space taken will be 0(n^2)\nfor recursive call stack will be n\ntotal = 0(n*n) + 0(n) = 0(n*n)\n\n# Code\n```\n/**\n * Definition for a binary tree node.\n * struct TreeNode {\n * int val;\n * TreeNode *left;\n * TreeNode *right;\n * TreeNode() : val(0), left(nullptr), right(nullptr) {}\n * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}\n * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}\n * };\n */\nclass Solution {\npublic:\n map<pair<int,int>,vector<TreeNode*>>dp;\n vector<TreeNode*>solve(int start , int end){\n if(start>end){\n return dp[{start,end}]={NULL};\n }\n\n if(start==end){\n TreeNode *temp = new TreeNode(start);\n return dp[{start,end}]={temp};\n }\n\n if(dp.find({start,end})!=dp.end()){\n return dp[{start,end}];\n }\n vector<TreeNode*>Result;\n for(int i=start; i<=end ; i++){\n auto a = solve(start, i-1);\n auto b = solve(i+1, end);\n\n for(auto node : a){\n for(auto c: b){\n auto root = new TreeNode(i);\n root->left = node;\n root->right=c;\n Result.push_back(root);\n }\n }\n }\n return dp[{start,end}]=Result;\n }\n vector<TreeNode*> generateTrees(int n) {\n\n return solve(1,n);\n \n\n }\n};\n```
4
0
['Dynamic Programming', 'Backtracking', 'Tree', 'Binary Search Tree', 'Recursion', 'Binary Tree', 'C++']
2
unique-binary-search-trees-ii
Recursion || Easy Solution || Using Left and right pointers
recursion-easy-solution-using-left-and-r-l1eu
Intuition\n Describe your first thoughts on how to solve this problem. \nBy using start and end variables to generate all the trees.\n\n# Approach\n Describe yo
M_S_L
NORMAL
2023-08-05T05:09:49.716959+00:00
2023-08-05T05:09:49.716981+00:00
20
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nBy using start and end variables to generate all the trees.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nNow let\'s look how our helper function will work!\n\n1. As there will be trees with root as 1, 2, 3...n. Iterate through all values from start to end to construct tree rooted at i and construct its left and right subtree recursively.\n2. We know that in Binary Search Tree all nodes in left subtree are smaller than root and in right subtree are larger than root. So for start = 1 and end = n, if we have ith number as root, all numbers from 1 to i-1 will be in left subtree and i+1 to n will be in right subtree.\nTherefore, we will build the tree recursively for left and right subtrees rooted at i as leftSubTree = bst(start, i-1) and rightSubtree = bst(i + 1, end)\nSo, till what moment we will recursively find the left and right subtrees?? Answer is until start < end!!\nSo when start > end, add NULL to the list and return\nThis will be our base case!\n3. Now, we have leftSubtree and rightSubtree for node with root i. The last thing we need to do is connect leftSubTree and rightSubTree with root and add this tree(rooted at i) to the ans list!\n\uD83D\uDCCC Here, we can have multiple left and right subtrees. So we need to loop through all left and right subtrees and connect every left subTree to right subTree and to current root(i) one by one.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n-> catalan Number(O(4^n/n^1.5)) * O(n) for generating the trees\n-> O(4^n/n^0.5).\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n-> recursion stack space.\n\n# Code\n```\n/**\n * Definition for a binary tree node.\n * struct TreeNode {\n * int val;\n * TreeNode *left;\n * TreeNode *right;\n * TreeNode() : val(0), left(nullptr), right(nullptr) {}\n * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}\n * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}\n * };\n */\nclass Solution {\npublic:\n vector<TreeNode*> generate(int i, int j) {\n vector<TreeNode*> res;\n if(i > j) {\n res.push_back(NULL);\n return res;\n }\n for(int ind = i;ind <= j;ind++) {\n vector<TreeNode*> left = generate(i, ind-1);\n vector<TreeNode*> right = generate(ind+1, j);\n for(auto l: left) {\n for(auto r: right) {\n TreeNode* root = new TreeNode(ind, l, r);\n res.push_back(root);\n }\n }\n }\n return res;\n }\n vector<TreeNode*> generateTrees(int n) {\n return generate(1, n);\n }\n};\n```
4
0
['Recursion', 'C++']
0
unique-binary-search-trees-ii
🔥🔥C++ Solution || ✅Recursion✅|| SuperEasy Explanation🔥🔥
c-solution-recursion-supereasy-explanati-ol78
Approach\n Describe your approach to solving the problem. \n1. The function generateTrees takes two parameters: n, which represents the number of nodes to be us
aa98-45556443355666
NORMAL
2023-08-05T04:38:11.509444+00:00
2023-08-05T09:22:37.242983+00:00
340
false
# Approach\n<!-- Describe your approach to solving the problem. -->\n1. The function `generateTrees` takes two parameters: `n`, which represents the number of nodes to be used for constructing BSTs, and `start`, which represents the starting value of the node range.\n\n2. The function uses recursion to generate all possible BSTs. The base case for the recursion is when n is less than start. In this case, the function returns a vector containing a single element with a value of `nullptr`. This is because there are no nodes available to construct a BST.\n\n3. If the base case is not triggered, the function proceeds with the generation of BSTs.\n\n4. The function initializes an empty vector `res` that will store the root nodes of all generated BSTs.\n\n5. It then iterates through a loop from `i = start` to `i = n`.\n Inside the loop, the function performs a nested loop for `leftSubTree` and `rightSubTree` using recursive calls to generateTrees.\n\n6. The recursive call `generateTrees(i - 1, start)` generates all possible `left subtrees` of the current root node with values ranging from `start to i - 1`.\n\n7. The recursive call `generateTrees(n, i + 1)` generates all possible `right subtrees` of the current root node with values ranging from `i + 1 to n`.\n\n8. For each combination of left and right subtrees, the function creates a new BST by creating a new TreeNode with the value `i` as the root and setting the left and right subtrees accordingly.The newly created BST\'s root node is added to the `res` vector.\n\n9. The process repeats for each i in the loop, generating different combinations of BSTs.\n\n10. After the loop is complete, the function returns the `res` vector, which contains pointers to the root nodes of all the generated BSTs.\n\n# Complexity\n***Here C(n) represents the nth Catalan number.***\n- Time complexity: $$O(C(n))$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:$$O(n * C(n))$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n/**\n * Definition for a binary tree node.\n * struct TreeNode {\n * int val;\n * TreeNode *left;\n * TreeNode *right;\n * TreeNode() : val(0), left(nullptr), right(nullptr) {}\n * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}\n * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}\n * };\n */\nclass Solution {\npublic:\n vector<TreeNode*> generateTrees(int n,int start=1) {\n \n //base case\n if(n<start){\n return {nullptr};\n }\n\n vector<TreeNode*> res;\n\n for(int i=start;i<=n;i++){\n for(auto leftSubTree:generateTrees(i-1,start)){\n for(auto rightSubTree:generateTrees(n,i+1)){\n res.push_back(new TreeNode(i,leftSubTree,rightSubTree));\n }\n\n }\n }\n\n return res;\n\n }\n};\n```\n\n![upvote lc.jpeg](https://assets.leetcode.com/users/images/4adc0ee4-e71a-45fd-bb4d-4fa397ebe276_1691227351.1175337.jpeg)\n
4
0
['Tree', 'Binary Search Tree', 'Recursion', 'Binary Tree', 'C++']
0
unique-binary-search-trees-ii
Python3 Solution
python3-solution-by-motaharozzaman1996-qchz
\n\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.l
Motaharozzaman1996
NORMAL
2023-08-05T04:18:25.848909+00:00
2023-08-05T04:18:25.848926+00:00
975
false
\n```\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def generateTrees(self, n: int) -> List[Optional[TreeNode]]:\n @lru_cache\n def dfs(start,end):\n if start>end:\n return [None]\n\n ans=[]\n for i in range(start,end+1):\n left=dfs(start,i-1)\n right=dfs(i+1,end)\n for l in left:\n for r in right:\n root=TreeNode(i)\n root.left=l\n root.right=r\n ans.append(root)\n return ans\n\n return dfs(1,n) \n```
4
0
['Python', 'Python3']
1
unique-binary-search-trees-ii
Most concise one to beat 99% | memoization | Java
most-concise-one-to-beat-99-memoization-j1ru9
Recursive to memoization\n\nsee recursive implementation here.\nThanks to @ArpAry.\n\n\nclass Solution {\n public List<TreeNode> generateTrees(int n) {\n
Nagaraj_Poojari
NORMAL
2023-06-04T15:17:37.050038+00:00
2023-06-04T15:17:37.050087+00:00
2,297
false
#### Recursive to memoization\n\nsee recursive implementation [here](https://leetcode.com/problems/unique-binary-search-trees-ii/solutions/3477600/95-unique-binary-search-trees-ii-java/?envType=study-plan-v2&envId=dynamic-programming).\nThanks to [@ArpAry](https://leetcode.com/ArpAry/).\n\n```\nclass Solution {\n public List<TreeNode> generateTrees(int n) {\n List<TreeNode>[][] dp=new ArrayList[n+1][n+1];\n return memo(1,n,dp);\n }\n List<TreeNode> memo(int s,int e,List<TreeNode>[][] dp){\n if(s>e){\n List<TreeNode> a=new ArrayList<>();\n a.add(null);\n return a;\n }\n if(dp[s][e]!=null) return dp[s][e];\n dp[s][e]=new ArrayList<>();\n for(int i=s;i<=e;i++){\n List<TreeNode> left=memo(s,i-1,dp);\n List<TreeNode> right=memo(i+1,e,dp);\n for(TreeNode l:left)\n for(TreeNode r:right)\n dp[s][e].add(new TreeNode(i,l,r));\n }\n return dp[s][e];\n }\n}\n```
4
0
['Recursion', 'Memoization', 'Java']
0
unique-binary-search-trees-ii
C# Divide and conquer, easy to understand
c-divide-and-conquer-easy-to-understand-q5p6x
Algorithm\n1. Pick a number i from 1 .. n\n2. Use it as the root of the current tree\n3. Solve 2 subproblems 1 .. i - 1 and i + 1 .. n\n4. Repeat for every i fr
maskalek
NORMAL
2023-03-02T06:39:40.512237+00:00
2023-03-02T06:39:40.512284+00:00
307
false
# Algorithm\n1. Pick a number `i` from `1 .. n`\n2. Use it as the root of the current tree\n3. Solve 2 subproblems `1 .. i - 1` and `i + 1 .. n`\n4. Repeat for every `i` from `1 .. n`\n\n# Code\n```\n/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * public int val;\n * public TreeNode left;\n * public TreeNode right;\n * public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\npublic class Solution {\n public IList<TreeNode> GenerateTrees(int n) {\n return GenerateTrees(1, n);\n }\n\n public IList<TreeNode> GenerateTrees(int left, int right)\n {\n var res = new List<TreeNode>();\n\n if(left > right)\n {\n res.Add(null);\n return res;\n }\n\n for(var i = left; i <= right; i++)\n {\n var leftNodes = GenerateTrees(left, i - 1);\n var rightNodes = GenerateTrees(i + 1, right);\n \n foreach(var leftNode in leftNodes)\n {\n foreach(var rightNode in rightNodes)\n {\n var node = new TreeNode(i, leftNode, rightNode);\n res.Add(node);\n }\n }\n }\n return res;\n }\n}\n```
4
0
['Divide and Conquer', 'C#']
1
unique-binary-search-trees-ii
c++ short solution || Recursion
c-short-solution-recursion-by-shristha-2cz9
\n\n# Code\n\n/**\n * Definition for a binary tree node.\n * struct TreeNode {\n * int val;\n * TreeNode *left;\n * TreeNode *right;\n * TreeNod
Shristha
NORMAL
2023-01-27T10:43:03.846198+00:00
2023-01-27T10:43:03.846229+00:00
2,835
false
\n\n# Code\n```\n/**\n * Definition for a binary tree node.\n * struct TreeNode {\n * int val;\n * TreeNode *left;\n * TreeNode *right;\n * TreeNode() : val(0), left(nullptr), right(nullptr) {}\n * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}\n * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}\n * };\n */\nclass Solution {\npublic:\n \n vector<TreeNode*> generate(int n,int start){\n if(start>n)return {NULL};\n vector<TreeNode*>res;\n for(int i=start;i<=n;i++){\n for(auto left:generate(i-1,start)){\n for(auto right:generate(n,i+1)){\n res.push_back(new TreeNode(i,left,right));\n }\n }\n }\n return res;\n }\n vector<TreeNode*> generateTrees(int n) {\n return generate(n,1);\n }\n};\n\n\n```
4
0
['Recursion', 'C++']
1
unique-binary-search-trees-ii
C++ recursion very fast (Minimum Line)
c-recursion-very-fast-minimum-line-by-ma-uoc0
\t\tclass Solution {\n\t\tpublic:\n\t\t\tvector generateTrees(int n, int s = 1) {\n\t\t\t\tvector ans;\n\t\t\t\tif(n < s) return {nullptr};
manishx112
NORMAL
2022-09-22T17:22:27.214317+00:00
2022-09-22T17:22:27.214359+00:00
2,061
false
\t\tclass Solution {\n\t\tpublic:\n\t\t\tvector<TreeNode*> generateTrees(int n, int s = 1) {\n\t\t\t\tvector<TreeNode*> ans;\n\t\t\t\tif(n < s) return {nullptr}; \n\t\t\t\t for(int i=s; i<=n; i++) { \t // Consider every number in range [s,n] as root \n\t\t\t\t\tfor(auto left: generateTrees(i-1, s)) { // generate all possible trees in range [s,i)\n\t\t\t\t\t\tfor(auto right: generateTrees(n, i+1)) // generate all possible trees in range (i,e]\n\t\t\t\t\t\t\tans.push_back(new TreeNode(i, left, right)); // make new trees with i as the root \n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn ans;\n\t\t\t}\n\t\t};
4
0
['Dynamic Programming', 'Recursion', 'C', 'C++']
1
unique-binary-search-trees-ii
"Trust Me boys and girls "-By Recursion
trust-me-boys-and-girls-by-recursion-by-xl6u1
Solution -->\n\nclass Solution {\npublic:\n \n vector<TreeNode*> generateBST(int begin, int end)\n {\n vector<TreeNode*> arr;\n \n
shubhaamtiwary_01
NORMAL
2022-08-16T16:32:19.579016+00:00
2022-08-16T16:32:19.579057+00:00
260
false
**Solution -->**\n```\nclass Solution {\npublic:\n \n vector<TreeNode*> generateBST(int begin, int end)\n {\n vector<TreeNode*> arr;\n \n if(begin>end)\n {\n arr.push_back(NULL);\n return arr;\n }\n \n for(int i=begin; i<=end; i++)\n {\n vector<TreeNode*>left = generateBST(begin, i-1);\n vector<TreeNode*>right = generateBST(i+1,end);\n \n for(auto l:left)\n {\n for(auto r:right)\n {\n TreeNode* root = new TreeNode();\n root->val = i;\n root->left = l;\n root->right = r;\n arr.push_back(root);\n }\n }\n \n }\n return arr;\n }\n \n vector<TreeNode*> generateTrees(int n) {\n \n vector<TreeNode*>arr;\n if(n==0) return arr;\n \n return generateBST(1,n);\n }\n};\n```\n
4
0
['Recursion', 'C']
0
unique-binary-search-trees-ii
JAVA || RECURSION || BEGINNER FRIENDLY
java-recursion-beginner-friendly-by-madd-08fy
\nclass Solution {\n public List<TreeNode> generateTrees(int n) {\n return solve(1,n) ;\n }\n \n public List<TreeNode> solve(int left,int rig
maddy310
NORMAL
2022-07-13T10:13:07.127136+00:00
2022-07-13T10:13:07.127164+00:00
710
false
```\nclass Solution {\n public List<TreeNode> generateTrees(int n) {\n return solve(1,n) ;\n }\n \n public List<TreeNode> solve(int left,int right){\n List<TreeNode> ans = new ArrayList<>() ;\n if(left > right){\n ans.add(null) ;\n return ans ;\n }\n for(int i = left ; i <= right ; i++){\n List<TreeNode> lft = solve(left,i-1) ;\n List<TreeNode> ryt = solve(i+1,right) ;\n for(TreeNode l : lft){\n for(TreeNode r : ryt){\n ans.add(new TreeNode(i,l,r)) ;\n }\n }\n }\n return ans ;\n }\n}\n```
4
0
['Recursion', 'Java']
0
unique-binary-search-trees-ii
easy understandable recursion solution (with comments)
easy-understandable-recursion-solution-w-u1sv
\nclass Solution {\npublic:\n vector<TreeNode*> generate(int start,int end){\n vector<TreeNode*> ans; // to store subtree for current node.\n
ravishankarnitr
NORMAL
2022-05-26T05:55:05.877271+00:00
2022-05-26T05:55:05.877304+00:00
286
false
```\nclass Solution {\npublic:\n vector<TreeNode*> generate(int start,int end){\n vector<TreeNode*> ans; // to store subtree for current node.\n if(start>end){ // means null\n ans.push_back(NULL);\n return ans;\n }\n \n for(int i=start;i<=end;i++){\n vector<TreeNode*> left_nodes=generate(start,i-1); // store all left child node here.\n vector<TreeNode*> right_nodes=generate(i+1,end); // store all right child node here.\n \n // with every left child and right child , form a tree and push it in ans array.\n for(auto left: left_nodes){\n for(auto right: right_nodes){\n TreeNode* root=new TreeNode(i,left,right);\n ans.push_back(root);\n }\n }\n }\n \n return ans;\n }\n \n vector<TreeNode*> generateTrees(int n) {\n return generate(1,n);\n }\n};\n```\n
4
0
['Recursion', 'C']
0
longest-subarray-of-1s-after-deleting-one-element
[Java/C++/Python] Sliding Window, at most one 0
javacpython-sliding-window-at-most-one-0-2f0m
Intuition\nAlmost exactly same as 1004. Max Consecutive Ones III\nGiven an array A of 0s and 1s,\nwe may change up to k = 1 values from 0 to 1.\nReturn the leng
lee215
NORMAL
2020-06-27T16:03:01.985512+00:00
2020-06-27T16:03:01.985559+00:00
35,727
false
# **Intuition**\nAlmost exactly same as 1004. [Max Consecutive Ones III](https://leetcode.com/problems/max-consecutive-ones-iii/discuss/247564/JavaC%2B%2BPython-Sliding-Window)\nGiven an array A of 0s and 1s,\nwe may change up to k = 1 values from 0 to 1.\nReturn the **length - 1** of the longest (contiguous) subarray that contains only 1s.\n\nI felt we discuss the same sliding window solution every two weeks..\nAnd I continue to receive complaints that I didn\'t give explantion again and again.\n<br>\n\n# **Complexity**\nTime `O(N)`\nSpace `O(1)`\n<br>\n\n# Solution 1:\nSliding window with at most one 0 inside.\n**Java**\n```java\n public int longestSubarray(int[] A) {\n int i = 0, j, k = 1, res = 0;\n for (j = 0; j < A.length; ++j) {\n if (A[j] == 0) {\n k--;\n }\n while (k < 0) {\n if (A[i] == 0) {\n k++;\n }\n i++;\n }\n res = Math.max(res, j - i);\n }\n return res;\n }\n```\n<br>\n\n# Solution 2\nSliding window that size doesn\'t shrink.\n**Java:**\n```java\n public int longestSubarray(int[] A) {\n int i = 0, j, k = 1;\n for (j = 0; j < A.length; ++j) {\n if (A[j] == 0) k--;\n if (k < 0 && A[i++] == 0) k++;\n }\n return j - i - 1;\n }\n```\n\n**C++:**\n```cpp\n int longestSubarray(vector<int>& A) {\n int i = 0, j, k = 1;\n for (j = 0; j < A.size(); ++j) {\n if (A[j] == 0) k--;\n if (k < 0 && A[i++] == 0) k++;\n }\n return j - i - 1;\n }\n```\n\n**Python:**\n```py\n def longestSubarray(self, A):\n k = 1\n i = 0\n for j in xrange(len(A)):\n k -= A[j] == 0\n if k < 0:\n k += A[i] == 0\n i += 1\n return j - i\n```\n<br>\n\n# More Similar Sliding Window Problems\nHere are some similar sliding window problems.\nAlso find more explanations and discussion.\nGood luck and have fun.\n\n- 5434. Longest Subarray of 1\'s After Deleting One Element\n- 1425. [Constrained Subsequence Sum](https://leetcode.com/problems/constrained-subsequence-sum/discuss/597751/JavaC++Python-O(N)-Decreasing-Deque)\n- 1358. [Number of Substrings Containing All Three Characters](https://leetcode.com/problems/number-of-substrings-containing-all-three-characters/discuss/516977/JavaC++Python-Easy-and-Concise)\n- 1248. [Count Number of Nice Subarrays](https://leetcode.com/problems/count-number-of-nice-subarrays/discuss/419378/JavaC%2B%2BPython-Sliding-Window-atMost(K)-atMost(K-1))\n- 1234. [Replace the Substring for Balanced String](https://leetcode.com/problems/replace-the-substring-for-balanced-string/discuss/408978/javacpython-sliding-window/367697)\n- 1004. [Max Consecutive Ones III](https://leetcode.com/problems/max-consecutive-ones-iii/discuss/247564/JavaC%2B%2BPython-Sliding-Window)\n- 930. [Binary Subarrays With Sum](https://leetcode.com/problems/binary-subarrays-with-sum/discuss/186683/)\n- 992. [Subarrays with K Different Integers](https://leetcode.com/problems/subarrays-with-k-different-integers/discuss/523136/JavaC%2B%2BPython-Sliding-Window)\n- 904. [Fruit Into Baskets](https://leetcode.com/problems/fruit-into-baskets/discuss/170740/Sliding-Window-for-K-Elements)\n- 862. [Shortest Subarray with Sum at Least K](https://leetcode.com/problems/shortest-subarray-with-sum-at-least-k/discuss/143726/C%2B%2BJavaPython-O(N)-Using-Deque)\n- 209. [Minimum Size Subarray Sum](https://leetcode.com/problems/minimum-size-subarray-sum/discuss/433123/JavaC++Python-Sliding-Window)\n<br>
374
15
[]
63
longest-subarray-of-1s-after-deleting-one-element
✅Beat's 100% || C++ || JAVA || PYTHON || Beginner Friendly🔥🔥🔥
beats-100-c-java-python-beginner-friendl-mher
Intuition:\nThe Intuition is to use a sliding window approach to find the length of the longest subarray of 1\'s after removing at most one element (0 or 1) fro
rahulvarma5297
NORMAL
2023-07-05T00:55:52.543264+00:00
2023-07-05T09:02:15.773696+00:00
44,562
false
# Intuition:\nThe Intuition is to use a sliding window approach to find the length of the longest subarray of 1\'s after removing at most one element (0 or 1) from the original array. It adjusts the window to have at most one zero, calculates the subarray length, and returns the maximum length found.\n\n# Explanation:\n\n1. The code aims to find the length of the longest subarray consisting of only 1\'s after deleting at most one element (0 or 1) from the original array.\n2. The variable `left` represents the left pointer of the sliding window, which defines the subarray.\n3. The variable `zeros` keeps track of the number of zeroes encountered in the current subarray.\n4. The variable `ans` stores the maximum length of the subarray found so far.\n5. The code iterates over the array using the right pointer `right`.\n6. If `nums[right]` is 0, it means we encountered a zero in the array. We increment `zeros` by 1.\n7. The while loop is used to adjust the window by moving the left pointer `left` to the right until we have at most one zero in the subarray.\n8. If `nums[left]` is 0, it means we are excluding a zero from the subarray, so we decrement `zeros` by 1.\n9. We update the `left` pointer by moving it to the right.\n10. After adjusting the window, we calculate the length of the current subarray by subtracting the number of zeroes from the total length `right - left + 1`. We update `ans` if necessary.\n11. Finally, we check if the entire array is the longest subarray. If it is, we subtract 1 from the maximum length to account for the one element we are allowed to delete. We return the resulting length.\n\n# Complexity:\n**Time complexity**: $$ O(N) $$\n- Each element in the array will be iterated over twice at max. Each element will be iterated over for the first time in the for loop; then, it might be possible to re-iterate while shrinking the window in the while loop. No element can be iterated more than twice.\n\n**Space complexity**: $$ O(1) $$\n\n# Code\n```C++ []\nclass Solution {\npublic:\n int longestSubarray(vector<int>& nums) {\n int n = nums.size();\n\n int left = 0;\n int zeros = 0;\n int ans = 0;\n\n for (int right = 0; right < n; right++) {\n if (nums[right] == 0) {\n zeros++;\n }\n while (zeros > 1) {\n if (nums[left] == 0) {\n zeros--;\n }\n left++;\n }\n ans = max(ans, right - left + 1 - zeros);\n }\n return (ans == n) ? ans - 1 : ans;\n }\n};\n```\n```Java []\nclass Solution {\n public int longestSubarray(int[] nums) {\n int n = nums.length;\n\n int left = 0;\n int zeros = 0;\n int ans = 0;\n\n for (int right = 0; right < n; right++) {\n if (nums[right] == 0) {\n zeros++;\n }\n while (zeros > 1) {\n if (nums[left] == 0) {\n zeros--;\n }\n left++;\n }\n ans = Math.max(ans, right - left + 1 - zeros);\n }\n return (ans == n) ? ans - 1 : ans;\n }\n}\n```\n```Python3 []\nclass Solution:\n def longestSubarray(self, nums: List[int]) -> int:\n n = len(nums)\n\n left = 0\n zeros = 0\n ans = 0\n\n for right in range(n):\n if nums[right] == 0:\n zeros += 1\n\n while zeros > 1:\n if nums[left] == 0:\n zeros -= 1\n left += 1\n\n ans = max(ans, right - left + 1 - zeros)\n\n return ans - 1 if ans == n else ans\n```\n\n# Code With Comments\n```C++ []\nclass Solution {\npublic:\n int longestSubarray(vector<int>& nums) {\n int n = nums.size(); // The size of the input array\n\n int left = 0; // The left pointer of the sliding window\n int zeros = 0; // Number of zeroes encountered\n int ans = 0; // Maximum length of the subarray\n\n for (int right = 0; right < n; right++) {\n if (nums[right] == 0) {\n zeros++; // Increment the count of zeroes\n }\n\n // Adjust the window to maintain at most one zero in the subarray\n while (zeros > 1) {\n if (nums[left] == 0) {\n zeros--; // Decrement the count of zeroes\n }\n left++; // Move the left pointer to the right\n }\n\n // Calculate the length of the current subarray and update the maximum length\n ans = max(ans, right - left + 1 - zeros);\n }\n\n // If the entire array is the subarray, return the size minus one; otherwise, return the maximum length\n return (ans == n) ? ans - 1 : ans;\n }\n};\n```\n```Java []\nclass Solution {\n public int longestSubarray(int[] nums) {\n int n = nums.length; // The size of the input array\n\n int left = 0; // The left pointer of the sliding window\n int zeros = 0; // Number of zeroes encountered\n int ans = 0; // Maximum length of the subarray\n\n for (int right = 0; right < n; right++) {\n if (nums[right] == 0) {\n zeros++; // Increment the count of zeroes\n }\n\n // Adjust the window to maintain at most one zero in the subarray\n while (zeros > 1) {\n if (nums[left] == 0) {\n zeros--; // Decrement the count of zeroes\n }\n left++; // Move the left pointer to the right\n }\n\n // Calculate the length of the current subarray and update the maximum length\n ans = Math.max(ans, right - left + 1 - zeros);\n }\n\n // If the entire array is the subarray, return the size minus one; otherwise, return the maximum length\n return (ans == n) ? ans - 1 : ans;\n }\n}\n```\n```Python3 []\nclass Solution:\n def longestSubarray(self, nums: List[int]) -> int:\n n = len(nums) # The size of the input array\n\n left = 0 # The left pointer of the sliding window\n zeros = 0 # Number of zeroes encountered\n ans = 0 # Maximum length of the subarray\n\n for right in range(n):\n if nums[right] == 0:\n zeros += 1 # Increment the count of zeroes\n\n # Adjust the window to maintain at most one zero in the subarray\n while zeros > 1:\n if nums[left] == 0:\n zeros -= 1 # Decrement the count of zeroes\n left += 1 # Move the left pointer to the right\n\n # Calculate the length of the current subarray and update the maximum length\n ans = max(ans, right - left + 1 - zeros)\n\n # If the entire array is the subarray, return the size minus one; otherwise, return the maximum length\n return ans - 1 if ans == n else ans\n```\n\n![CUTE_CAT.png](https://assets.leetcode.com/users/images/dab2e6fb-869c-4c38-8ef6-c03a451c101b_1688518513.326088.png)\n\n\n**If you found my solution helpful, I would greatly appreciate your upvote, as it would motivate me to continue sharing more solutions.**
315
0
['Sliding Window', 'C++', 'Java', 'Python3']
16
longest-subarray-of-1s-after-deleting-one-element
Java O(n) time, O(1) space, no sliding window
java-on-time-o1-space-no-sliding-window-ibhkf
Just calculate the max sum of counts of prev Ones and after Ones for each non-ones;\nprevCnt: counts of prev Ones\ncnt: counts of Ones after.\npitfalls:\nif al
hobiter
NORMAL
2020-06-27T18:22:33.087305+00:00
2020-06-28T23:49:47.373746+00:00
6,976
false
Just calculate the max sum of counts of prev Ones and after Ones for each non-ones;\nprevCnt: counts of prev Ones\ncnt: counts of Ones after.\npitfalls:\nif all ones, must remove one;\n\nO(n) time, O(1) space, concise and straightforward\n\n```\n public int longestSubarray(int[] nums) {\n int prevCnt = 0, cnt = 0, res = 0;\n for (int i = 0; i < nums.length; i++) {\n if (nums[i] == 1) cnt++;\n else {\n res = Math.max(res, cnt + prevCnt);\n prevCnt = cnt;\n cnt = 0;\n }\n }\n res = Math.max(res, cnt + prevCnt);\n return res == nums.length ? res - 1 : res; //if all ones, must remove one;\n }\n```
126
1
[]
17
longest-subarray-of-1s-after-deleting-one-element
[Python] O(n) dynamic programming, detailed explanation
python-on-dynamic-programming-detailed-e-e252
One way to deal this problem is dynamic programming. Let dp[i][0] be the length of longest subarray of ones, such that it ends at point i. Let dp[i][1] be the l
dbabichev
NORMAL
2020-06-27T16:02:50.972351+00:00
2020-06-27T16:02:50.972413+00:00
6,726
false
One way to deal this problem is **dynamic programming**. Let `dp[i][0]` be the length of longest subarray of ones, such that it ends at point `i`. Let `dp[i][1]` be the length longest subarray, which has one **zero** and ends at point `i`. Let us traverse through our `nums` and update our `dp` table, we have two options:\n\n0. `dp[0][0] = 1` if `nums[0] = 1` and `0` in opposite case.\n1. If `nums[i] = 1`, than to update `dp[i][0]` we just need to look into `dp[i-1][0]` and add one, the same true is for `dp[i][1]`.\n2. If `nums[i] = 0`, than `dp[i][0] = 0`, we need to interrupt our sequence without zeroes. `dp[i][1] = dp[i-1][0]`, because we we added `0` and number of `1` is still `i-1`. \n\nLet us go through example `[1,0,1,1,0,0,1,1,0,1,1,1]`:\nthen we have the following `dp` table:\n\n| 1 | 0 | 1 | 2 | 0 | 0 | 1 | 2 | 0 | 1 | 2 | 3 |\n|-------|-------|-------|-------|-------|-------|-------|-------|-------|-------|-------|-------|\n| **0** | **1** | **2** | **3** | **2** | **0** | **1** | **2** | **2** | **3** | **4** | **5** |\n\n\n**Complexity**: time and space is `O(n)`, because we iterate over our table `dp` once. Space can be reduced to `O(1)` because we only look into the previous column of our table.\n\n**Extension and follow-up**. Note, that this solution can be easily extended for the case, when we need to delete `k` elements instead of one, with time complexity `O(nk)` and space complexity `O(k)`.\n\n**Other solutions**. This problem can be solved with sliding window technique as well, or we can evaluate sizes of groups of `0`\'s and `1`\'s and then choose two group of `1`\'s, such that it has group of `0`\'s with only one element between them. \n\n\n```\nclass Solution:\n def longestSubarray(self, nums):\n n = len(nums)\n if sum(nums) == n: return n - 1\n \n dp = [[0] * 2 for _ in range(n)]\n dp[0][0] = nums[0]\n \n for i in range(1, n):\n if nums[i] == 1:\n dp[i][0], dp[i][1] = dp[i-1][0] + 1, dp[i-1][1] + 1\n else:\n dp[i][0], dp[i][1] = 0, dp[i-1][0]\n \n return max([i for j in dp for i in j]) \n```\n\nIf you have any questions, feel free to ask. If you like solution and explanations, please **Upvote!**
121
4
['Dynamic Programming']
10
longest-subarray-of-1s-after-deleting-one-element
[Java/Python 3] Sliding Window with at most one zero w/ detailed explanation and brief analysis.
javapython-3-sliding-window-with-at-most-fd8l
Two methods.\n\n----\nMethod 1:\n1. Use i and j as the lower and upper bounds, both inclusively;\n2. Loop through the nums by upper bound, accumulate current el
rock
NORMAL
2020-06-27T16:10:56.221473+00:00
2023-01-18T13:55:19.749290+00:00
7,838
false
Two methods.\n\n----\n**Method 1:**\n1. Use `i` and `j` as the lower and upper bounds, both inclusively;\n2. Loop through the `nums` by upper bound, accumulate current element on the `sum`, then check if `sum` is less than `j - i` (which **implies the window includes at least 2 `0`s**) : if yes, keep increase the lower bound `i` till either the sliding window has at most `1` zero or lower bound is same as upper bound;\n\n**Core concept here:** - credit to **@lionkingeatapple and @abhinav_7**.\n`sum` count the number of `1`s in the window.\n`j - i` means `the length of the window - 1`. Since we need to delete one element which is zero from this window, we use `j - i` not `j - i + 1`.\nSpecifically, if \n```\nsum == (j - i) + 1\n```\nthen all `1`\'s exist in the window`(i - j)`; if \n```\nsum == (j - i)\n```\none zero exist; if \n```\nsum < (j - i)\n```\nmore than one zeros exist!\n\nWith those two conditions above, we can know if the number of ones in the window is less than the length of the window minus `1`, then we have least two zeros in this window. In other words, we want to find a window that only contains a single zero and the rest of the elements are all ones. Let me give an example below.\n```\n window = [1, 1, 1, 0, 0] \n index = 0, 1, 2, 3, 4\n```\nThe `sum = 3` when `i = 0, j = 3`. We have a qualified window, and `j - i = 3 - 0 = 3` means we have only one zero. When `i = 0, j = 4`, and `j - i = 4 - 0 = 4` means we have two zeros, so we need to move our left bound `i` of the window.\n\n3. Update the max value of the sliding window.\n\n```java\n public int longestSubarray(int[] nums) {\n int ans = 0;\n for (int i = 0, j = 0, sum = 0; j < nums.length; ++j) {\n sum += nums[j];\n while (i < j && sum < j - i) {\n sum -= nums[i++];\n }\n ans = Math.max(ans, j - i);\n }\n return ans;\n }\n```\n```python\n def longestSubarray(self, nums: List[int]) -> int:\n ans = sum = lo = 0\n for hi, num in enumerate(nums):\n sum += num\n while lo < hi and sum < hi - lo:\n sum -= nums[lo]\n lo += 1\n ans = max(ans, hi - lo)\n return ans \n```\n\n----\n\n**Method 2: minor optimization**, similar to method 1 but the window will not shrink.\n\n```java\n public int longestSubarray(int[] nums) {\n int ans = 0;\n for (int i = 0, j = 0, sum = 0; j < nums.length; ++j) {\n sum += nums[j];\n if (sum < j - i) {\n sum -= nums[i++];\n }\n ans = Math.max(ans, j - i);\n }\n return ans;\n }\n```\n```python\n def longestSubarray(self, nums: List[int]) -> int:\n ans = sum = lo = 0\n for hi, num in enumerate(nums):\n sum += num\n if sum < hi - lo:\n sum -= nums[lo]\n lo += 1\n ans = max(ans, hi - lo)\n return ans\n```\n\n**Analysis:**\n\nTime: O(n), space: O(1).\n\n----\nPlease refer to the following for similar problems:\n\n[209. Minimum Size Subarray Sum](https://leetcode.com/problems/minimum-size-subarray-sum/description/)\n[862. Shortest Subarray with Sum at Least K](https://leetcode.com/problems/shortest-subarray-with-sum-at-least-k/description/)\n[904. Fruit Into Baskets](https://leetcode.com/problems/fruit-into-baskets/description/)\n[930. Binary Subarrays With Sum](https://leetcode.com/problems/binary-subarrays-with-sum/description/)\n[992. Subarrays with K Different Integers](https://leetcode.com/problems/subarrays-with-k-different-integers/description/)\n[1004. Max Consecutive Ones III](https://leetcode.com/problems/max-consecutive-ones-iii/description/)\n[1234. Replace the Substring for Balanced String](https://leetcode.com/problems/replace-the-substring-for-balanced-string/description/)\n[1248. Count Number of Nice Subarrays](https://leetcode.com/problems/count-number-of-nice-subarrays/description/)\n[1358. Number of Substrings Containing All Three Characters](https://leetcode.com/problems/number-of-substrings-containing-all-three-characters/description/)\n[1425. Constrained Subsequence Sum](https://leetcode.com/problems/constrained-subsequence-sum/description/)\n\n----\n\nDo let me know if you can make the codes better, and **Upvote** if they are helpful for you.
57
1
['Sliding Window', 'Java', 'Python3']
6
longest-subarray-of-1s-after-deleting-one-element
Python, Java | Elegant & Short | One pass | O(n) time | O(1) memory
python-java-elegant-short-one-pass-on-ti-4ftg
Python:\n\n\ndef longestSubarray(self, nums: List[int]) -> int:\n\tlongest = prev = curr = 0\n\n\tfor bit in nums:\n\t\tif bit:\n\t\t\tcurr += 1\n\t\t\tlongest
Kyrylo-Ktl
NORMAL
2022-09-22T16:07:49.757109+00:00
2022-09-30T13:17:04.160094+00:00
4,945
false
## Python:\n\n```\ndef longestSubarray(self, nums: List[int]) -> int:\n\tlongest = prev = curr = 0\n\n\tfor bit in nums:\n\t\tif bit:\n\t\t\tcurr += 1\n\t\t\tlongest = max(longest, prev + curr)\n\t\telse:\n\t\t\tprev, curr = curr, 0\n\n\treturn longest - (longest == len(nums))\n```\n\n## Java:\n\n```\npublic int longestSubarray(int[] nums) {\n\tint longest = 0;\n\tint prev = 0, curr = 0;\n\n\tfor (int bit : nums) {\n\t\tif (bit == 0) {\n\t\t\tprev = curr;\n\t\t\tcurr = 0;\n\t\t} else {\n\t\t\tlongest = Math.max(longest, prev + ++curr);\n\t\t}\n\t}\n\n\treturn longest == nums.length ? longest - 1 : longest;\n}\n```\n\nIf you like this solution remember to **upvote it** to let me know.
48
0
['Python', 'Java', 'Python3']
3
longest-subarray-of-1s-after-deleting-one-element
100% fast | C++ | Java | Python | Easy Line by Line Explanation + Video Explanation
100-fast-c-java-python-easy-line-by-line-ni2e
\n# Intuition\n Describe your first thoughts on how to solve this problem. \nHere we can figure out that max one subarray will be formed when we \ndelete any 0
shivam-727
NORMAL
2023-07-05T04:02:06.470422+00:00
2023-08-15T20:18:21.949337+00:00
6,169
false
\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nHere we can figure out that max one subarray will be formed when we \ndelete any 0 from array\n\nFor detailed explanation you can refer to my youtube channel (Hindi Language)\n https://youtu.be/RXWLIqpDosY\n or link in my profile.Here,you can find any solution in playlists monthwise from june 2023 with detailed explanation.i upload daily leetcode solution video with short and precise explanation (5-10) minutes.\nor\nsearch \uD83D\uDC49`Longest subarray of 1s after deleting one element by Let\'s Code Together` on youtube\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nSliding Window\n\n1. Initialize two pointers `i` and `j` to track the start and end indices of the subarray, respectively. Also, initialize variables `n` as the size of the input array `nums`, `c0` as the count of zeros encountered so far, and `mx` as the maximum length of the subarray.\n\n2. Start iterating over the array using the `j` pointer until it reaches the end (`n`). For each element `nums[j]`:\n - If the current element is zero (`nums[j] == 0`), increment the count of zeros (`c0++`).\n\n3. Enter a nested while loop with the condition `while (i < n && c0 == 2)` to handle the case when there are more than one zeros in the current subarray.\n - Check from element at the start index (`nums[i]`) is zero (`nums[i] == 0`).\n - If it is zero, decrement the count of zeros (`c0--`) to indicate that we have removed one zero from the subarray.\n - Increment the start index (`i++`) to shrink the subarray from the left side.we will strink until count of zeroes becomes less than 2\n\n4. Calculate the length of the current subarray (`j - i`) and update the maximum length (`mx`) if necessary.\n\n5. Increment the `j` pointer to move the sliding window to the right for the next iteration.\n\n6. Repeat steps 2-5 until we have iterated over the entire array.\n\n7. Return the maximum length of the subarray (`mx`) as the result.\n\nPlease Upvote if you find this useful\n\n# Complexity\n- Time complexity:$$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:$$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# C++ Code\n```\nclass Solution {\npublic:\n int longestSubarray(vector<int>& nums) {\n int i=0;\n int j=0;\n int n=nums.size();\n int c0=0;\n int mx=0;\n while(j<n){\n if(nums[j]==0){\n c0++;\n }\n while(i<n&&c0==2){\n if(nums[i]==0){\n c0--;\n }\n i++;\n }\n mx=max(j-i,mx);\n j++;\n }\n return mx;\n }\n};\n```\n# Java Code\n```\nclass Solution {\n public int longestSubarray(int[] nums) {\n int i = 0;\n int j = 0;\n int n = nums.length;\n int c0 = 0;\n int mx = 0;\n while (j < n) {\n if (nums[j] == 0) {\n c0++;\n }\n while (i < n && c0 == 2) {\n if (nums[i] == 0) {\n c0--;\n }\n i++;\n }\n mx = Math.max(j - i, mx);\n j++;\n }\n return mx;\n }\n}\n\n```\n# Python Code\n```\nclass Solution:\n def longestSubarray(self, nums):\n i = 0\n j = 0\n n = len(nums)\n c0 = 0\n mx = 0\n while j < n:\n if nums[j] == 0:\n c0 += 1\n while i < n and c0 == 2:\n if nums[i] == 0:\n c0 -= 1\n i += 1\n mx = max(j - i, mx)\n j += 1\n return mx\n\n```\nplease upvote\uD83D\uDE42 this motivates me to share daily solutions
25
0
['Array', 'Sliding Window', 'Python', 'C++', 'Java']
2
longest-subarray-of-1s-after-deleting-one-element
Sliding Window
sliding-window-by-votrubac-dokl
C++\ncpp\nint longestSubarray(vector<int>& nums) {\n int max_sz = 0;\n for (int i = 0, j = 0, skip = 0; i < nums.size(); ++i) {\n skip += nums[i] =
votrubac
NORMAL
2020-06-27T16:02:51.343711+00:00
2022-04-01T13:55:43.826183+00:00
3,160
false
**C++**\n```cpp\nint longestSubarray(vector<int>& nums) {\n int max_sz = 0;\n for (int i = 0, j = 0, skip = 0; i < nums.size(); ++i) {\n skip += nums[i] == 0;\n if (skip > 1)\n skip -= nums[j++] == 0;\n max_sz = max(max_sz, i - j);\n }\n return max_sz;\n}\n```
24
3
['C']
1
longest-subarray-of-1s-after-deleting-one-element
🏆C++ || Sliding Window EASY
c-sliding-window-easy-by-chiikuu-u7h9
Code\n\nclass Solution {\npublic:\n int longestSubarray(vector<int>& nums) {\n int l=0,r=0;\n int mx=0,count=0,total=0;\n while(r<nums.s
CHIIKUU
NORMAL
2023-07-05T05:01:23.456344+00:00
2023-07-05T05:01:23.456380+00:00
7,079
false
# Code\n```\nclass Solution {\npublic:\n int longestSubarray(vector<int>& nums) {\n int l=0,r=0;\n int mx=0,count=0,total=0;\n while(r<nums.size()){\n if(nums[r]==0){\n count++;\n while(count>1){\n if(nums[l]==0)count--;\n else total--;\n l++;\n }\n }\n else{\n total++;\n mx = max(mx,total);\n }\n r++;\n }\n if(mx==nums.size())mx--;\n return mx;\n }\n};\n```\n![upvote (2).jpg](https://assets.leetcode.com/users/images/f4881088-0e17-4298-b8b6-4aac93e2cb46_1688533275.1867304.jpeg)\n
23
0
['C++']
1
longest-subarray-of-1s-after-deleting-one-element
Just a clever sliding window
just-a-clever-sliding-window-by-slowbutf-xjgk
\nclass Solution {\npublic:\n int longestSubarray(vector<int>& nums) {\n int zero=0;\n int i=0,j=0,res=0;\n while(j<nums.size()){\n
slowbutfast
NORMAL
2020-06-27T18:01:27.791675+00:00
2020-06-27T18:01:27.791712+00:00
2,680
false
```\nclass Solution {\npublic:\n int longestSubarray(vector<int>& nums) {\n int zero=0;\n int i=0,j=0,res=0;\n while(j<nums.size()){\n if(nums[j]==0)\n zero++;\n if(zero>1){\n while(nums[i++]!=0);\n zero--;\n }\n res=max(res,j-i); // we don\'t write j-i+1 because we need to give its length after removing the zero\n j++;\n }\n return res;\n }\n};\n```
22
1
[]
8
longest-subarray-of-1s-after-deleting-one-element
[Python] Sliding window solution explained
python-sliding-window-solution-explained-myxc
\nclass Solution:\n def longestSubarray(self, nums: List[int]) -> int:\n res = 0\n k = 1 # max zeroes we can delete\n l = 0\n \n
buccatini
NORMAL
2022-02-06T04:35:06.205705+00:00
2022-02-06T04:35:06.205736+00:00
2,384
false
```\nclass Solution:\n def longestSubarray(self, nums: List[int]) -> int:\n res = 0\n k = 1 # max zeroes we can delete\n l = 0\n \n for r in range(len(nums)):\n # if we encounter a zero, decrement\n # the num zeroes we can now delete\n if nums[r] == 0:\n k -= 1\n\n # if we\'ve seen more than one zero\n # move the left pointer until we\n # have discarded the first zero\n # we have encountered hence making the\n # sliding window (l..r) valid again\n while k < 0 and l <= r:\n if nums[l] == 0:\n k += 1\n l += 1\n \n # make sure you\'re not adding +1\n # to the sliding window because we\n # want to also account for the deleted\n # zero, so don\'t index correct here\n res = max(res, r-l)\n \n return res\n```
20
0
['Sliding Window', 'Python', 'Python3']
2
longest-subarray-of-1s-after-deleting-one-element
[Easy Solution without DP] Simple Pictorial Explanation | Python Solution.
easy-solution-without-dp-simple-pictoria-w6av
Explanation\n\n\n\nCode\n\nclass Solution:\n def longestSubarray(self, nums: List[int]) -> int:\n m=0\n l=len(nums)\n one=True\n
lazerx
NORMAL
2020-06-27T16:03:20.719690+00:00
2022-01-09T18:06:48.690321+00:00
1,982
false
**Explanation**\n![image](https://assets.leetcode.com/users/images/282e2259-4117-419d-9d4e-899b02886ec4_1593273700.8198037.png)\n\n\n**Code**\n```\nclass Solution:\n def longestSubarray(self, nums: List[int]) -> int:\n m=0\n l=len(nums)\n one=True\n for i in range(0,l):\n if nums[i]==0:\n one=False\n left=i-1\n right=i+1\n ones=0\n while left>=0:\n if nums[left]==1:\n ones=ones+1\n left=left-1\n else:\n break\n while right<l:\n if nums[right]==1:\n ones=ones+1\n right=right+1\n else:\n break\n if ones>m:\n m=ones\n if one:\n return l-1\n return m\n```\nLike if you find it helpful.
18
5
['Python', 'Python3']
5
longest-subarray-of-1s-after-deleting-one-element
Beats 100% + Video | Java C++ Pyhton
beats-100-video-java-c-pyhton-by-jeevank-b3gf
\n\n\nclass Solution {\n public int longestSubarray(int[] nums) {\n int prev = 0; int curr = 0;\n int ans = 0;\n for(int i: nums){\n
jeevankumar159
NORMAL
2023-07-05T01:35:33.800157+00:00
2023-07-05T01:37:59.288800+00:00
2,703
false
<iframe width="560" height="315" src="https://www.youtube.com/embed/jhBrybXSFTs" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe>\n\n```\nclass Solution {\n public int longestSubarray(int[] nums) {\n int prev = 0; int curr = 0;\n int ans = 0;\n for(int i: nums){\n if(i==1) curr++;\n else{\n ans = Math.max(ans,curr+prev);\n prev = curr;\n curr = 0;\n }\n }\n ans = Math.max(ans, curr+prev);\n \n return ans==nums.length?ans-1:ans;\n }\n}\n```\n\n```\nclass Solution {\npublic:\n int longestSubarray(std::vector<int>& nums) {\n int prev = 0, curr = 0;\n int ans = 0;\n for (int i : nums) {\n if (i == 1)\n curr++;\n else {\n ans = std::max(ans, curr + prev);\n prev = curr;\n curr = 0;\n }\n }\n ans = std::max(ans, curr + prev);\n\n return (ans == nums.size()) ? ans - 1 : ans;\n }\n};\n```\n\n```\nclass Solution:\n def longestSubarray(self, nums: List[int]) -> int:\n prev = 0\n curr = 0\n ans = 0\n for i in nums:\n if i == 1:\n curr += 1\n else:\n ans = max(ans, curr + prev)\n prev = curr\n curr = 0\n ans = max(ans, curr + prev)\n\n return ans-1 if ans == len(nums) else ans\n```
16
0
['C', 'Python', 'Java']
3
longest-subarray-of-1s-after-deleting-one-element
🔥[Python3] Sliding windows with shrinking and not shrinking size
python3-sliding-windows-with-shrinking-a-ncly
The window size is r - l + 1, but because here in the window we should remove 1 symbol (it can be 1 or 0) the window size will be r - l. \nThe condition prefix
yourick
NORMAL
2023-07-05T05:30:52.027135+00:00
2023-12-04T16:13:21.733027+00:00
1,828
false
The window size is `r - l + 1`, but because here in the window we should remove 1 symbol (it can be `1` or `0`) the window size will be `r - l`. \nThe condition `prefix < r - l` means that in the window more than one `0`.\n\n###### Window can be invalid, shrink not more than 1 symbol for every iteration if window is invalid. At the end `r - l` is max possible window size.\n```python3 []\nclass Solution:\n def longestSubarray(self, nums: List[int]) -> int:\n res, l, prefix = 0, 0, 0\n for r, n in enumerate(nums):\n prefix += n\n if prefix < r - l:\n prefix -= nums[l]\n l += 1\n return r - l\n```\n###### The window can\'t be invalid, every time we change window size while it\'s invalid and update max result. Here to optimisation we can save the last zero position and move left pointer `l` to `lastZeroPosition + 1`. But for this case will be better to calculate the number of zeros in prefix instead of number of ones like in the current solution.\n```python3 []\nclass Solution:\n def longestSubarray(self, nums: List[int]) -> int:\n res, l, prefix = 0, 0, 0\n for r, n in enumerate(nums):\n prefix += n\n while prefix < r-l:\n prefix -= nums[l]\n l += 1\n res = max(res, r-l)\n return res\n```
15
0
['Sliding Window', 'Python', 'Python3']
0
longest-subarray-of-1s-after-deleting-one-element
c++ easy solution using simple for loop
c-easy-solution-using-simple-for-loop-by-hgy7
\nclass Solution {\npublic:\n int longestSubarray(vector<int>& nums) {\n int a=0,b=0,c=0;\n for(int i=0;i<nums.size();++i){\n if(num
rknimkande1781
NORMAL
2022-08-25T19:36:06.345222+00:00
2022-08-25T19:36:06.345252+00:00
1,832
false
```\nclass Solution {\npublic:\n int longestSubarray(vector<int>& nums) {\n int a=0,b=0,c=0;\n for(int i=0;i<nums.size();++i){\n if(nums[i]==1){\n a++;\n }else{\n b=a;\n a=0;\n }\n c=max(c,b+a);\n }\n \n if(c==nums.size())\n return c-1;\n else\n return c; \n \n }\n};\n\n```
15
1
['C', 'C++']
4
longest-subarray-of-1s-after-deleting-one-element
Concise Clean Code! Different Solution | Similar Pattern
concise-clean-code-different-solution-si-0dx9
Status: Accepted\nExplanation:\n toLeft[i] Stores the consecutive ones which is present left of i\n toRight[i] Stores the consecutive ones which is present righ
applefanboi
NORMAL
2020-06-27T16:01:23.289206+00:00
2020-06-30T13:08:10.130644+00:00
1,355
false
**Status**: Accepted\n**Explanation**:\n* toLeft[i] Stores the consecutive ones which is present left of i\n* toRight[i] Stores the consecutive ones which is present right of i\n* If we delete a element the ones in the subarray must be consecutive ones to the right and left.\n\n**Similar Problem:** [Maximum Subarray Sum with one deletion](https://leetcode.com/problems/maximum-subarray-sum-with-one-deletion/)\n**Complexity Analysis**:\n1. Time: O(N)\n2. Space: O(N)\n\n```\nclass Solution {\npublic:\n int longestSubarray(vector<int>& nums) {\n int n = nums.size();\n vector<int> toLeft(n), toRight(n);\n \n \n toLeft[0] = 0;\n for(int i = 1; i < nums.size(); i++){\n toLeft[i] = nums[i - 1] ? toLeft[i - 1] + 1 : 0;\n }\n \n toRight[n - 1] = 0;\n for(int i = n - 2; i >= 0; i--){\n toRight[i] = nums[i + 1] ? toRight[i + 1] + 1 : 0;\n }\n int res = max(toRight[0], toLeft[n - 1]);\n for(int i = 0; i < n; i++){\n res = max(res, toLeft[i] + toRight[i]);\n }\n return res;\n }\n};\n```
14
2
['C', 'C++']
0
longest-subarray-of-1s-after-deleting-one-element
Easy Python Code
easy-python-code-by-hakkiot-ubvm
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
hakkiot
NORMAL
2023-07-05T02:36:39.327797+00:00
2023-07-05T02:36:39.327814+00:00
1,471
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def longestSubarray(self, nums: List[int]) -> int:\n prev=0\n count=0\n ls=[]\n visit=False\n for i in nums:\n if i==0:\n visit=True\n ls.append(prev+count)\n prev=count\n count=0\n if i==1:\n count+=1\n if not visit:\n count-=1\n ls.append(count+prev)\n return max(ls)\n```
13
0
['Python3']
1
longest-subarray-of-1s-after-deleting-one-element
C++ | using iteration |
c-using-iteration-by-ashish_madhup-lfna
Intuition\n Describe your first thoughts on how to solve this problem. Upon analyzing the code, it appears that the objective of the longestSubarray function is
ashish_madhup
NORMAL
2023-07-05T04:42:51.288125+00:00
2023-07-05T04:42:51.288157+00:00
1,775
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->Upon analyzing the code, it appears that the objective of the `longestSubarray` function is to find the length of the longest subarray in a given vector of integers (`a`). The subarray should satisfy the condition that it can be obtained by removing exactly one element (either a 0 or a 1) from the original array.\n\nTo approach this problem, I would consider the following steps:\n\n1. Initialize variables to keep track of the maximum subarray length (`maxLen`), the size of the input array (`n`), and a vector (`zeros`) to store the indices of zeros in the array.\n2. Iterate through the input array and identify the indices of all zeros. Store these indices in the `zeros` vector.\n3. Add virtual indices (-1 before the first element and `n` after the last element) to the `zeros` vector to simplify the calculations.\n4. Iterate through the `zeros` vector and calculate the length of subarrays between consecutive zeros. Keep track of the maximum length encountered so far (`maxLen`).\n5. If there are only two zeros in the `zeros` vector, it means the entire array can be considered as a subarray by removing one element. In this case, return `n - 1`.\n6. Finally, return the maximum subarray length (`maxLen`) obtained.\n\nBy following these steps, we can identify the length of the longest subarray satisfying the given conditions.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->My approach to solving the problem would be as follows:\n\n1. Initialize a variable `maxLen` to keep track of the maximum subarray length.\n2. Determine the size of the input array `n`.\n3. Create a vector `zeros` to store the indices of zeros in the array. Start by pushing a virtual index `-1` before the first element.\n4. Iterate through the input array and check for zeros. Whenever a zero is encountered, add its index to the `zeros` vector.\n5. Push a virtual index `n` after the last element to simplify calculations.\n6. Determine the number of zeros in the `zeros` vector as `zerosCount`.\n7. Iterate through the `zeros` vector from the second element to the second-to-last element.\n - Calculate the length of the subarray between the current zero and the two adjacent zeros.\n - Update `maxLen` if the calculated length is greater.\n8. If there are only two zeros in the `zeros` vector, it means the entire array can be considered as a subarray by removing one element. In this case, return `n - 1`.\n9. Finally, return the maximum subarray length `maxLen`.\n\nThis approach ensures that we consider all possible subarrays by removing one element (either a 0 or a 1) and keep track of the maximum length encountered.\n\n# Complexity\n- Time complexity: O(n + k)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(k)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int longestSubarray(vector<int>& nums) {\n int maxLen = 0; // Maximum length of subarray\n int n = nums.size(); // Size of input array\n vector<int> zeros; // Indices of zeros in the input array\n zeros.push_back(-1); // Start with a virtual index before the first element\n \n // Find indices of zeros in the input array\n for (int i = 0; i < n; i++) {\n if (nums[i] == 0)\n zeros.push_back(i);\n }\n \n zeros.push_back(n); // End with a virtual index after the last element\n \n int zerosCount = zeros.size(); // Number of zeros\n \n // Calculate the length of subarrays between consecutive zeros and update maxLen\n for (int i = 1; i < zerosCount - 1; i++) {\n int currLen = zeros[i + 1] - zeros[i - 1] - 2;\n maxLen = max(maxLen, currLen);\n }\n \n // If there are only two zeros, the longest subarray can be the entire array except one element\n if (zerosCount == 2)\n return n - 1;\n \n return maxLen;\n }\n};\n\n```\n![Leetcode.jpeg](https://assets.leetcode.com/users/images/3063e305-f6b7-4a3c-a43d-87ba09837e5b_1688532068.5500627.jpeg)\n
12
0
['Array', 'Dynamic Programming', 'Sliding Window', 'C++']
1
longest-subarray-of-1s-after-deleting-one-element
[BEATS 95%] 🔥BEGINNER FRIENDLY | ONE PASS, SIMPLE ROLLING SUM
beats-95-beginner-friendly-one-pass-simp-pumz
Intuition/Approach\n Describe your first thoughts on how to solve this problem. \nIf the array has zeros, then we want to delete the zero that has the most cons
aaronlw
NORMAL
2023-07-05T00:47:05.442823+00:00
2023-07-05T01:00:48.801385+00:00
1,965
false
# Intuition/Approach\n<!-- Describe your first thoughts on how to solve this problem. -->\nIf the array has zeros, then we want to delete the zero that has the most consecutive ones surrounding both sides of it. We use prevSum and curSum to track the number of consecutive ones to the left and right of each zero. At the end, we add curSum and preSum to account for the final pair of left and right ones. If there are no zeros in the array, we subtract one from our final output, since we have to delete one from the array.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(1)\n\n# Code\n```\nclass Solution:\n def longestSubarray(self, nums: List[int]) -> int:\n prevSum, curSum, best, zeroFound = 0, 0, 0, False\n for i in range(len(nums)):\n if nums[i] == 1: \n curSum += 1\n if nums[i] == 0:\n best = max(prevSum + curSum, best)\n prevSum = curSum\n curSum = 0\n zeroFound = True\n return max(curSum + prevSum, best) - 1 if not zeroFound else max(curSum + prevSum, best)\n```
12
0
['Python3']
6
longest-subarray-of-1s-after-deleting-one-element
Simple java solution
simple-java-solution-by-siddhant_1602-vj36
Complexity\n- Time complexity: O(n)\n\n- Space complexity: O(n)\n\n# Code\n\nclass Solution {\n public int longestSubarray(int[] nums) {\n int count=0
Siddhant_1602
NORMAL
2023-07-05T04:12:56.583190+00:00
2023-07-05T04:12:56.583220+00:00
4,461
false
# Complexity\n- Time complexity: $$O(n)$$\n\n- Space complexity: $$O(n)$$\n\n# Code\n```\nclass Solution {\n public int longestSubarray(int[] nums) {\n int count=0;\n List<Integer> nm=new ArrayList<>();\n for(int i=0;i<nums.length;i++)\n {\n if(nums[i]==0)\n {\n if(count>0)\n {\n nm.add(count);\n count=0;\n }\n nm.add(0);\n }\n else\n {\n count++;\n }\n }\n nm.add(count);\n if(nm.size()==1)\n {\n return nums.length-1;\n }\n if(nm.size()==2)\n {\n return Math.max(nm.get(0),nm.get(1));\n }\n int max=0;\n for(int i=0;i<nm.size()-2;i++)\n {\n max=Math.max(max,nm.get(i)+nm.get(i+2));\n }\n return max;\n }\n}\n```
11
0
['Sliding Window', 'Java']
1
longest-subarray-of-1s-after-deleting-one-element
EASIEST C++ CODE (HIGHLY UNDERSTANDABLE)
easiest-c-code-highly-understandable-by-f462m
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
baibhavsingh07
NORMAL
2023-07-05T03:40:41.228372+00:00
2023-07-05T03:40:41.228395+00:00
2,362
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(N)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int longestSubarray(vector<int>& a) {\n int i,j,k,c=0,s=0,m=0;\n vector<int>v;\n v.push_back(-1);\n for(i=0;i<a.size();i++){\n if(a[i]==0)\n v.push_back(i);\n }\n v.push_back(i);\n\n for(i=1;i<v.size()-1;i++){\n m=max(m,v[i+1]-v[i-1]-2);\n }\n if(v.size()==2)\n return a.size()-1;\n\n return m;\n \n }\n};\n```
11
1
['Array', 'Sliding Window', 'C++']
0