Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit d4d98c7

Browse files
committed
Add solution #95
1 parent 98903f4 commit d4d98c7

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed

0095-unique-binary-search-trees-ii.js

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
/**
2+
* 95. Unique Binary Search Trees II
3+
* https://leetcode.com/problems/unique-binary-search-trees-ii/
4+
* Difficulty: Medium
5+
*
6+
* Given an integer n, return all the structurally unique BST's (binary search
7+
* trees), which has exactly n nodes of unique values from 1 to n. Return the
8+
* answer in any order.
9+
*/
10+
11+
/**
12+
* Definition for a binary tree node.
13+
* function TreeNode(val, left, right) {
14+
* this.val = (val===undefined ? 0 : val)
15+
* this.left = (left===undefined ? null : left)
16+
* this.right = (right===undefined ? null : right)
17+
* }
18+
*/
19+
/**
20+
* @param {number} n
21+
* @return {TreeNode[]}
22+
*/
23+
var generateTrees = function(n) {
24+
return backtrack(n);
25+
};
26+
27+
function backtrack(n, j = 1, k = n, result = []) {
28+
for (let index = j; index <= k; index++) {
29+
for (const left of backtrack(n, j, index - 1)) {
30+
for (const right of backtrack(n, index + 1, k)) {
31+
result.push({ val: index, left, right });
32+
}
33+
}
34+
}
35+
36+
return n ? result.length ? result : [null] : [];
37+
}

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,7 @@
7878
90|[Subsets II](./0090-subsets-ii.js)|Medium|
7979
93|[Restore IP Addresses](./0093-restore-ip-addresses.js)|Medium|
8080
94|[Binary Tree Inorder Traversal](./0094-binary-tree-inorder-traversal.js)|Easy|
81+
95|[Unique Binary Search Trees II](./0095-unique-binary-search-trees-ii.js)|Medium|
8182
98|[Validate Binary Search Tree](./0098-validate-binary-search-tree.js)|Medium|
8283
100|[Same Tree](./0100-same-tree.js)|Easy|
8384
101|[Symmetric Tree](./0101-symmetric-tree.js)|Easy|

0 commit comments

Comments
 (0)