Q7: Unique Binary Search Trees

时间:2023-03-09 22:13:28
Q7: 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.

    \       /     /      / \      \

    /     /       \                 \
                                  

解决原理1:

遍历+递归

二叉查找树的根节点可以是1~n中的任何一个数i

根为i的二叉树数量=左子树数量*右子树数量

左子树的根节点取值范围为1~i,右子树的根节点取值范围为i+1~n,i+1~n组成的二叉查找树的数量又与1~n-i的相同

代码1:

 class Solution {
int sum;
public:
int numTrees(int n) {
if(n == ) return ;
if(n == ) return ;
for(int i = ; i <= n; i++){
int l = numTrees(i-);
int r = numTrees(n-i);
sum = sum + (l==?:l) * (r==?:r);
}
return sum;
}
};

但是,此方法超时