0
点赞
收藏
分享

微信扫一扫

Leetcode96. 不同的二叉搜索树


题目传送:​​https://leetcode.cn/problems/unique-binary-search-trees/submissions/​​

运行效率

Leetcode96. 不同的二叉搜索树_二叉搜索树


代码如下:

public static int numTrees(int n) {
int num = generateNum(1, n);
return num;
}

public static int generateNum(int start, int end) {
int count = 0;
//处理边界情况
if (start == end) {
return 1;
}
//1、先确定二叉搜索树的根节点
for (int i = start; i <= end; i++) {
int leftNum = 1;
int rightNum = 1;
if (i - 1 >= start) {
//左边二叉树的所有可能情况数
leftNum = generateNum(start, i - 1);
}
//右边二叉树的所有可能情况数
if (i + 1 <= end) {
rightNum = generateNum(i + 1, end);
}
count +=leftNum*rightNum;
}
return count;
}


举报

相关推荐

0 条评论