Problem
Given an integer n, generate all structurally unique BST's (binary search trees) that store values 1 … n.
Example:
Input: 3
Output:
[
[1,null,3,2],
[3,2,null,1],
[3,1,null,null,2],
[2,1,3],
[1,null,2,null,3]
]
Explanation:
The above output corresponds to the 5 unique BST's shown below:
1 3 3 2 1
\ / / / \ \
3 2 1 1 3 2
/ / \ \
2 1 2 3
Solution
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {number} n
* @return {TreeNode[]}
*/
var generateTrees = function(n) {
if (n < 1) return [];
return generate(1, n);
};
var generate = function (l, r) {
var nodes = [];
var node = null;
var left = [];
var right = [];
for (var i = l; i <= r; i++) {
left = generate(l, i - 1);
right = generate(i + 1, r);
for (var j = 0; j < left.length; j++) {
for (var k = 0; k < right.length; k++) {
node = new TreeNode(i);
node.left = left[j];
node.right = right[k];
nodes.push(node);
}
}
}
return nodes.length ? nodes : [null];
};
Explain:
例如:有 5
个节点,选取其中 1
个作为 root
,还剩 4
个。则左右可分为 (0, 4), (1, 3), (2, 2), (3, 1), (4, 0)
等几种情况,左右的分配用递归得到即可。
Complexity:
- Time complexity :
- Space complexity :