###### Leetcode之unique-binary-search-trees

Given n, how many structurally unique BST’s (binary search trees) that store values 1…n?

For example,
Given n = 3, there are a total of 5 unique BST’s.

n == 0 时，空树的个数必然为1，因此bsTreeNum[0] = 1
n == 1 时，只有1这个根节点，数量也为1，因此bsTreeNum[1] = 1
n == 2时，
bsTreeNum[2] = bsTreeNum[0] * bsTreeNum[1] +bsTreeNum[1] * bsTreeNum[0]
n == 3时，
bsTreeNum[3] = bsTreeNum[0] * bsTreeNum[2] + bsTreeNum[1] * bsTreeNum[1] +bsTreeNum[2] * bsTreeNum[0]

package suda.alex.leetcode;

import java.util.Scanner;

public class UniqueBSTree {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scanner = new Scanner(System.in);
System.out.println("input n:");
int n = scanner.nextInt();
System.out.println("the number of BST is:" + numTrees(n));
}
public static int numTrees(int n) {
if(n == 0){
return 1;
}
int[] bsTreeNum = new int[n+1];
bsTreeNum[0] = 1;
bsTreeNum[1] = 1;
for(int i=2;i<=n;i++){
for(int j=0;j<i;j++){
bsTreeNum[i] += bsTreeNum[j]*bsTreeNum[i-j-1];
}
}
return bsTreeNum[n];

}

}


#### Unique Binary Search Trees II -- LeetCode

2014-04-30 06:15:46

#### Unique Binary Search Trees -- LeetCode

2014-04-30 06:16:29

#### LeetCode || Unique Binary Search Trees

2014-04-09 23:16:41

#### 【leetcode】unique-binary-search-trees

2014-08-24 10:24:34

#### leetcode — unique-binary-search-trees

2018-02-28 09:11:54

#### 4.27 leetcode -27 unique-binary-search-trees

2017-08-30 22:05:17

#### 【unique-binary-search-trees】

2017-09-10 08:18:12

#### unique-binary-search-trees

2017-04-24 22:07:50

#### 刷LeetCode刷LeetCode刷LeetCode刷LeetCode

2018年01月09日 1.55MB 下载

#### leetcode试题的答案

2018年01月14日 101KB 下载

## 不良信息举报

Leetcode之unique-binary-search-trees