Skip to main content

Unique Binary Search Trees II

Problem statement

Given an integer n, return all the structurally unique BST's (binary search trees), which has exactly n nodes of unique values from 1 to n. Return the answer in any order.

Example 1:

Input: n = 3Output: [[1,null,2,null,3],[1,null,3,2],[2,1,3],[3,1,null,null,2],[3,2,null,1]]

Example 2:

Input: n = 1Output: [[1]]

Constraints:

  • 1 <= n <= 8

My solution

/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {number} n
* @return {TreeNode[]}
*/
var generateTrees = function(n) {
if (n === 0) {
return []
}
return traverse(1, n)
};

function traverse(left, right) {
let result = [];

if (left === right) {
return [new TreeNode(left)]
}

if (right < left) {
return [null]
}

for (let i = left; i <= right; i++) {
const leftNode = traverse(left, i - 1)
const rightNode = traverse(i + 1, right)

for (let j = 0; j < leftNode.length; j++) {
for (let k = 0; k < rightNode.length; k++) {
const node = new TreeNode(i)
// console.log("i", node)
node.left = leftNode[j]
node.right = rightNode[k]
result.push(node)
}
}
}

// console.log(result)


return result;
}