2011-05-31 97 views
4

給定一組整數找出有多少獨特的二進制搜索樹可以構建出來?唯一的二進制搜索樹

根據我的答案取決於整數集的大小。如果該組整數的大小是n ..然後「N」獨特的二叉搜索樹可以做出來的吧..

我不知道答案..我是嗎?

+0

沒有用的樹... – soandos 2011-05-31 17:01:17

+0

「唯一整數的數量」,你的意思是「集合中唯一整數的數量嗎?」集合的數學定義不允許重複元素,因此「集合中唯一整數的數量」與集合的大小是相同的。 (如果這不是你的意思......好吧,有無數個整數。) – 2011-05-31 17:01:49

+0

[有'N'個節點,可能有多少個不同的二進制和二進制搜索樹?](http:// stackoverflow.com/questions/3042412/with-n-no-of-nodes-how-many-different-binary-and-binary-search-trees-possibl) – 2011-05-31 17:21:33

回答

1

該數字是C_n,其中C_n是第n Catalan Number。可以遞歸地定義該值,方法是選取n個節點中的任何一個作爲根,然後採取所有可能的方法來組織根的左右子樹,導致以下遞歸關係:

C_n = sum_ {i = 0}^{N - 1} C_I * C_ {N - 1 - I},

其中C_0 = 1

2

這可以通過使用動態編程來解決。

numTrees(i+1)=append the last node to the rightmost leaf of bst(i)[numTrees(i)] + 
       append the last node as the root of bst(i)[numTrees(i)] + 
       insert the last node as non-leaf node sum(k=1...i)(bst(k-1)*bst(i-k) 

因此它是o(n^2)解決方案。

public int numTrees(int n) { 
    if(n == 0 || n == 1 || n == 2) 
     return n; 
    int bst[] = new int[n+1]; 
    bst[0] = 1; 
    bst[1] = 1; 
    bst[2] = 2; 
    for (int i=3; i<=n; i++) { 
     for (int j=1; j<i-1; j++) { 
      bst[i] += bst[j]*bst[i-1-j]; 
     } 
     bst[i] += 2*bst[i-1]; 
    } 
    return bst[n]; 
}