# 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];

}

}


• 本文已收录于以下专栏：

举报原因： 您举报文章：Leetcode之unique-binary-search-trees 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)