96. Unique Binary Search Trees

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.

给出一个数字n,由从1到n这n个数字可以组成多少个结构互异的二叉树

对于一颗有n个节点的二叉树,选定一个根节点,其左子树和右子树的数目会是:
(0,n-1)、(1,n-2)、(2,n-3)......(n-1,0)
这就构成了这个二叉树所有互异的结构。
所以一个节点数目为n的二叉树的互异的树的数目为:
f(n) = f(0) * f(n-1) + f(1) * f(n-2) +......+f(n-1) * f(0)

var numTrees = function(n) {
    var G = [];
    G[0] = G[1] = 1;
    for(var i=2; i<=n; i++) {
        for(var j=1; j<=i; j++) {
            if (G[i]===undefined)
                G[i] = 0;
            G[i] += G[j-1] * G[i-j];
        }
    }
    return G[n];
};

你可能感兴趣的:(96. Unique Binary Search Trees)