[LeetCode_96] Unique Binary Search Trees
题目链接
https://leetcode.com/problems/unique-binary-search-trees/
题意
计算给定节点数的BST有多少种
思路
递归
相关知识
二叉搜索树(Binary Search Tree ,BST)
A BST is defined as follows:
1 The left subtree of a node contains only nodes with keys less than the node's key.
2 The right subtree of a node contains only nodes with keys greater than the node's key.
3 Both the left and right subtrees must also be binary search trees.
特点:
1.每个节点的值大于其任意左侧子节点的值,小于其任意右节点的值。
2.平衡时性能逼近二分查找,但相比连续内存空间的二分查找,插入删除操作开销更小,但多次插入删除可能造成树的不平衡,最坏接近线性查找。
代码
class Solution {
public:
int numTrees(int n) {
if(n==0||n==1){return 1;}
else{
int BSTCnt=0;
for(int i=1;i<=n;i++){
BSTCnt+=numTrees(i-1)*numTrees(n-i);
}
return BSTCnt;
}
}
};
reference
posted on 2019-01-22 20:56 coding_gaga 阅读(280) 评论(0) 编辑 收藏 举报
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步