题目:
Given n, generate all structurally unique BST's (binary search trees) that store values 1...n.
For example,
Given n = 3, your program should return all 5 unique BST's shown below.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 []; } return createTrees(1,n);};function createTrees(start,end){ var results=[]; if(start>end){ results.push(null); return results; } for(var i=start;i<=end;i++){ var left=createTrees(start,i-1); var right=createTrees(i+1,end); for(var j=0;j