题目:不同的二叉查找树
来源:互联网 发布:斑马梦龙网络计划介绍 编辑:程序博客网 时间:2024/05/22 15:22
通过给出 n,问由 1...n 为节点组成的不同的二叉查找树有多少种?
您在真实的面试中是否遇到过这个题?
Yes
样例
给出n = 3,有5种不同形态的二叉查找树:
1 3 3 2 1
\ / / / \ \
3 2 1 1 3 2
/ / \ \
2 1 2 3
标签 Expand
相关题目 Expand
解题思路:
注意:二分查找树的定义是,左子树节点均小于root,右子树节点均大于root!不要想当然地将某个点作为root时,认为其他所有节点都能全部放在left/right中,除非这个点是 min 或者 max 的。
分析:本题其实关键是递推过程的分析,n个点中每个点都可以作为root,当 i 作为root时,小于 i 的点都只能放在其左子树中,大于 i 的点只能放在右子树中,此时只需求出左、右子树各有多少种,二者相乘即为以 i 作为root时BST的总数。
http://blog.csdn.net/jiadebin890724/article/details/23305915
public class Solution { /** * @paramn n: An integer * @return: An integer */ public int numTrees(int n) { // write your code here if(n<0) return 0;<pre class="java" name="code">public class Solution { /** * @paramn n: An integer * @return: An integer */ public int numTrees(int n) { // write your code here if(n<0) return 0; if(n==0) return 1; int nums[] = new int[n+1]; for(int i=1;i<=n;i++){ nums[0] = 1; if(i<3){ nums[i] = i; }else{ for(int j=1;j<=i;j++){ nums[i] +=nums[j-1]*nums[i-j]; } } } return nums[n]; }}
if(n==0) return 1; int nums[] = new int[n+1]; for(int i=1;i<=n;i++){ nums[0] = 1; if(i<3){ nums[i] = i; }else{ for(int j=1;j<=i;j++){ nums[i] +=nums[j-1]*nums[i-j]; } } } return nums[n]; }}
0 0
- 题目:不同的二叉查找树
- 题目:不同的二叉查找树 II
- 不同的二叉查找树
- 不同的二叉查找树
- 不同的二叉查找树
- 不同的二叉查找树
- 关于二叉查找树的一些题目
- LintCode-不同的二叉查找树 II
- LintCode-不同的二叉查找树
- lintcode-不同的二叉查找树-163
- LintCode 不同的二叉查找树
- 不同的二叉查找树 II
- LintCode:不同的二叉查找树
- 不同的二叉查找树 II lintcode
- lintcode,不同的二叉查找树
- LintCode 163-不同的二叉查找树
- LintCode :不同的二叉查找树
- lintcode-不同的二叉查找树
- 关于openGL的深度测试
- 题目:下一个排列
- hdu 5417 Victor and Machine 思考题
- 黑马程序员----标识符和访问修饰符
- Qt 插件篇
- 题目:不同的二叉查找树
- 黑马程序员----String字符串、内部类和异常
- POJ3685--Matrix
- BC 52 div2 A Victor and Machine
- 如何写些用于装逼的JavaScript代码
- JavaScript 入门必读
- [扫盲]介绍一下GFW的工作原理和封锁技术
- 设计模式-结构型之代理模式
- 学习小结20150822