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.
1 3 3 2 1 \ / / / \ 3 2 1 1 3 2 / / \ 2 1 2 3
给定一个数字n, 问用1,2,3,4,5...n这n个值,能构造多少棵合法的二叉搜索树
class Solution { public: int binaryTreeNums(int start, int end){ //[start, end]区间上构造二叉树的数目 if(start>=end)return 1; //start<end表示空子树, start==end表示叶子节点 int treeNums=0; for(int root=start; root<=end; root++){ int leftCount = binaryTreeNums(start, root-1); //计算左子树的数目 int rightCount = binaryTreeNums(root+1, end); //计算右子树的数目 treeNums+= leftCount*rightCount; } return treeNums; } int numTrees(int n) { if(n==0)return 0; return binaryTreeNums(1, n); } };
LeetCode: Unique Binary Search Trees [095],布布扣,bubuko.com
LeetCode: Unique Binary Search Trees [095]
原文地址:http://blog.csdn.net/harryhuang1990/article/details/27958273