题目描述:
给定一个整数 n,生成所有由 1 … n 为节点所组成的二叉搜索树。
示例:
输入: 3
输出:
[
[1,null,3,2],
[3,2,null,1],
[3,1,null,null,2],
[2,1,3],
[1,null,2,null,3]
]
解释:
以上的输出对应以下 5 种不同结构的二叉搜索树:
1 3 3 2 1
\ / / / \ \
3 2 1 1 3 2
/ / \ \
2 1 2 3
代码实现:
/**
* 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 === 0) return []
if (n === 1) return [new TreeNode(1)]
var res = [new TreeNode(1), new TreeNode(2)]
res[0].right = new TreeNode(2)
res[1].left = new TreeNode(1)
var num = 3
while (num <= n) {
var cache = []
res.forEach(root => {
var newRoot = new TreeNode(num)
newRoot.left = root
cache.push(newRoot)
var node = root
while (node) {
newN = new TreeNode(num)
var newNode = new TreeNode(node.val)
newNode.left = node.left
newNode.right = newN
newN.left = node.right
var newRoot = node === root ? newNode : copyTree(root, newNode)
cache.push(newRoot)
node = node.right
}
})
res = cache
num++
}
return res
function copyTree(root, target) {
var res = new TreeNode(root.val), parent = res
while (root.right) {
var node = new TreeNode(root.right.val)
if (root.right.val === target.val) {
parent.right = target
parent.left = root.left
break
}
parent.right = node
parent.left = root.left
parent = node
root = root.right
}
return res
}
};