码迷,mamicode.com
首页 > 其他好文 > 详细

lintcode 中等题:unique Binary Search Tree 不同的二叉查找树

时间:2015-11-10 21:07:32      阅读:183      评论:0      收藏:0      [点我收藏+]

标签:

题目

给出 n,问由 1...n 为节点组成的不同的二叉查找树有多少种?

样例

给出n = 3,有5种不同形态的二叉查找树:

1           3    3       2      1
 \         /    /       / \        3      2     1       1   3      2
 /      /       \                  2     1          2                  3

解题

技术分享
public class Solution {
    /**
     * @paramn n: An integer
     * @return: An integer
     */
    public int numTrees(int n) {
        // write your code here
        int[] count = new int[n + 1];
        if( n==0 )
            return 1;
        count[0] = 1;
        count[1] = 1;
 
        for (int i = 2; i <= n; i++) {
            for (int j = 0; j <= i - 1; j++) {
                count[i] = count[i] + count[j] * count[i - j - 1];
            }
        }
        return count[n];
    }
}
Java Code

 



lintcode 中等题:unique Binary Search Tree 不同的二叉查找树

标签:

原文地址:http://www.cnblogs.com/theskulls/p/4951379.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!