Unique Binary Search Trees

来源:互联网 发布:值得买源码 编辑:程序博客网 时间:2024/06/04 18:54
题目:

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=1时只有1种,n=2时有2种。当n=i(i>2)时,考虑左右子树,若左子树有j个点,则右子树有i-j-1个点,减一是因为必须存在根节点,j可以等于0,此时此子树只有1个可能。所以n=3可以看成是左右子树为02,11,20的3种组合,每个组合等于左右子树的种类乘积。所以依次可以求得n时的BST种类

0 0
原创粉丝点击