[LeetCode] Unqiue Binary Search Trees I

来源:互联网 发布:写composer php插件 编辑:程序博客网 时间:2024/04/27 15:11

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

相关问题:返回所有可能的BST。

思路:很简单,用递归。

    int numTrees(int n) {        if(n==0)            return 1;                    if(n==1)            return 1;                    int total = 0;        for(int i=0; i<n; i++)        {            total = total+numTrees(i)*numTrees(n-i-1);        }                return total;    }



0 0
原创粉丝点击