码迷,mamicode.com
首页 > 编程语言 > 详细

[LeetCode][JavaScript]Unique Binary Search Trees II

时间:2015-11-08 23:45:01      阅读:228      评论:0      收藏:0      [点我收藏+]

标签:

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                 3
https://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 };

 

 

[LeetCode][JavaScript]Unique Binary Search Trees II

标签:

原文地址:http://www.cnblogs.com/Liok3187/p/4948528.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!