博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
唯一二叉搜索树
阅读量:6949 次
发布时间:2019-06-27

本文共 1677 字,大约阅读时间需要 5 分钟。

hot3.png

原题

  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         3     3      2      1    \       /     /      / \      \     3     2     1      1   3      2    /     /       \                 \   2     1         2                 3

 

 

题目大意

  给定一个n个结点的二叉搜索树,求一共有多少个不同类型的二叉搜索树。

解题思路

 当n=1时,只有1个根节点,则只能组成1种形态的二叉树,令n个节点可组成的二叉树数量表示为h(n),则h(1)=1; h(0)=0;  当n=2时,1个根节点固定,还有2-1个节点。这一个节点可以分成(1,0),(0,1)两组。即左边放1个,右边放0个;或者左边放0个,右边放1个。即:h(2)=h(0)*h(1)+h(1)*h(0)=2,则能组成2种形态的二叉树。  当n=3时,1个根节点固定,还有2个节点。这2个节点可以分成(2,0),(1,1),(0,2)3组。即h(3)=h(0)*h(2)+h(1)*h(1)+h(2)*h(0)=5,则能组成5种形态的二叉树。  以此类推,当n>=2时,可组成的二叉树数量为h(n)=h(0)*h(n-1)+h(1)*h(n-2)+...+h(n-1)*h(0)种,即符合Catalan数的定义,可直接利用通项公式得出结果。  令h(1)=1,h(0)=1,catalan数(卡特兰数)满足递归式:  h(n)= h(0)*h(n-1)+h(1)*h(n-2) + ... + h(n-1)h(0) (其中n>=2)  另类递归式:  h(n)=((4*n-2)/(n+1))*h(n-1);  该递推关系的解为:  h(n)=C(2n,n)/(n+1) (n=1,2,3,...)

  递推公式

  f(k)*f(n-1-k):f(k)表示根结点左子树有k个结点,其有的形状是f(k),f(n-1-k)表示右子树有n-1-k个结点
  f(n) = 2*f(n-1) + f(1)*f(n-2) + f(2)*f(n-3) + f(3)*f(n-4) + … +f(n-2)*f(1)

代码实现

实现类

public class Solution {    public int numTrees(int n) {        if (n <= 0) {            return 0;        } else if (n == 1) {            return 1;        }        int[] result = new int[n + 1];        result[0] = 0;        result[1] = 1;        // 求f(2)...f(n)        for (int i = 2; i <= n; i++) {            // 求f(i)            result[i] = 2 * result[i - 1];            for (int j = 1; j <= i - 1 ; j++) {                result[i] += result[j]*result[i - 1 -j];            }        }        return result[n];    }}

转载于:https://my.oschina.net/u/2822116/blog/808764

你可能感兴趣的文章
[转]Core Audio
查看>>
UIScrollView的属性总结
查看>>
unicode 和utf-8,GBK编码
查看>>
php 设置模式 单元素模式(单例模式或单件模式)
查看>>
Linux下升级python版本
查看>>
正则表达式全集
查看>>
iOS开发小技巧--修改按钮内部图片和文字之间的间距(xib)
查看>>
[转]原始套接字编程
查看>>
经典海量jQuery插件
查看>>
如何在博客园随笔中增加章节导航
查看>>
eclipse中的.project 和 .classpath文件的具体作用
查看>>
ubuntu 绑定固定ip
查看>>
(转)linux下fork的运行机制
查看>>
vue-cli搭建及项目目录结构
查看>>
springboot秒杀课程学习整理1-5
查看>>
css中display:none与visibility: hidden的区别
查看>>
本人精心收集的近80个国内最好的嵌入式技术相关网站和论坛和博客
查看>>
Python Package——wget
查看>>
在python下进行pdf的合并
查看>>
pyextend库-unpack列表集合字符串解包函数
查看>>