【LeetCode】96. Unique Binary Search Trees

来源:互联网 发布:域名工信部备案 编辑:程序博客网 时间:2024/05/03 10:24

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

class Solution {public:    int numTrees(int n) {                long long c=1;        for(int i=1;i<=n;i++){            c=2*c*(2*(i-1)+1)/((i-1)+2);        }                return c;    }   };
解题思路

嗯,这个题目的思想就是n个结点能够组成的不同的二叉树的个数是满足卡特兰数的。

另一个问题关于出栈顺序的的也用到了在这里:

点击打开链接

这里我使用了递推公式

然后还要使用long long int 才能解决这样的问题啊

应该有更好的解决方法

0 0
原创粉丝点击