[LeetCode][JavaScript]Unique Binary Search Trees II
Unique Binary Search Trees II
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 3https://leetcode.com/problems/unique-binary-search-trees-ii/#
生成n个节点的二叉排序树。
跟上一题一样的思路,分治,从1到n遍历,选当前的点为根,比根小的在左子树,比根大的在右子树。
http://www.cnblogs.com/Liok3187/p/4948510.html
1 /** 2 * Definition for a binary tree node. 3 * function TreeNode(val) { 4 * this.val = val; 5 * this.left = this.right = null; 6 * } 7 */ 8 /** 9 * @param {number} n 10 * @return {TreeNode[]} 11 */ 12 var generateTrees = function(n) { 13 return getTree(1, n); 14 15 function getTree(start, end){ 16 var ret = [], i, j, k, left, right, node; 17 if(start > end){ 18 return [null]; 19 }else if (start === end){ 20 return [new TreeNode(start)]; 21 } 22 for(i = start; i <= end; i++){ 23 left = getTree(start, i - 1); 24 right = getTree(i + 1, end); 25 for(j = 0; j < left.length; j++){ 26 for(k = 0; k < right.length; k++){ 27 node = new TreeNode(i); 28 node.left = left[j]; 29 node.right = right[k]; 30 ret.push(node); 31 } 32 } 33 } 34 return ret; 35 } 36 };