Skip to content

Commit b84af9b

Browse files
committedJan 24, 2023
Add solution #95
1 parent 86ad763 commit b84af9b

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed
 

‎README.md

+1
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|
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+
}

0 commit comments

Comments
 (0)
Please sign in to comment.