155 - 96 不同的二叉搜索树
Last updated
Was this helpful?
Last updated
Was this helpful?
给定一个整数 n,求以 1 ... n 为节点组成的二叉搜索树有多少种?
示例:
输入: 3 输出: 5 解释: 给定 n = 3, 一共有 5 种不同结构的二叉搜索树:
1 3 3 2 1 / / / 3 2 1 1 3 2 / / 2 1 2 3
设n个节点存在二叉排序树的个数是G(n)
设f(i)为以i为根的二叉搜索树的个数
那么$G(n)=f(1)+f(2)+f(3)+f(4)+...+f(n)$
那么$f(i)=G(i-1)*G(n-1)$
因为是二叉搜索树,左边的子节点,都要比$i$小,共有$i-1$个;右边子节点,都要比$i$大,共$n-i$个
所以带入得
$G(n)=G(0)∗G(n−1)+G(1)∗G(n−2)+...+G(n−1)∗G(0)$
Runtime: 24 ms, faster than 96.30% of Python3 online submissions for Unique Binary Search Trees.
Memory Usage: 12.6 MB, less than 100.00% of Python3 online submissions for Unique Binary Search Trees.
Runtime: 56 ms, faster than 53.22% of JavaScript online submissions for Unique Binary Search Trees.
Memory Usage: 33.9 MB, less than 33.33% of JavaScript online submissions for Unique Binary Search Trees.
Runtime: 0 ms, faster than 100.00% of Go online submissions for Unique Binary Search Trees.
Memory Usage: 2 MB, less than 100.00% of Go online submissions for Unique Binary Search Trees.
简言之有个公式可以算出来这个
Runtime: 24 ms, faster than 96.30% of Python3 online submissions for Unique Binary Search Trees.
Memory Usage: 12.8 MB, less than 100.00% of Python3 online submissions for Unique Binary Search Trees.
Runtime: 0 ms, faster than 100.00% of Go online submissions for Unique Binary Search Trees.
Memory Usage: 2 MB, less than 100.00% of Go online submissions for Unique Binary Search Trees.
Runtime: 48 ms, faster than 91.71% of JavaScript online submissions for Unique Binary Search Trees.
Memory Usage: 33.7 MB, less than 66.67% of JavaScript online submissions for Unique Binary Search Trees.