简体   繁体   English

二叉搜索树的数量

[英]The number of binary search trees

What is the number of binary search trees with 20 nodes with elements 1,2,3,...,20 such that the root of the tree is 12 and the root of the left sub tree is 7 ? 有20个节点且元素1,2,3,...,20的二叉搜索树的数量是多少,使得树的根为12,左子树的根为7? a) 2634240 b) 1243561 c) 350016 d) 2642640 a)2634240 b)1243561 c)350016 d)2642640

An explanation along with the answer would be helpful. 给出答案的解释会有所帮助。

I have applied the Catalan number formula but the result is inappropriate from the options, so this is just to be sure. 我已经应用了加泰罗尼亚语数字公式,但是从选项中得出的结果是不合适的,因此可以肯定的是。

Using the Catalan numbers , counting full binary trees with n nodes, the answer would be d) 2642640 = 14 * 132 * 1430. That's the possibilities extending (sub)trees from each of our unknown subtrees. 使用加泰罗尼亚数字 ,用n节点计数完整的二叉树,答案将是d) 2642640 = 14 * 132 *1430。这就是从我们每个未知子树扩展(子)树的可能性。

           12
          /  \
         7    (8 nodes)
        / \
(6 nodes) (4 nodes)


Update : 更新

As suggested by Mark Dickinson in the comments below, to clarify: the "nodes" mentioned in the diagram above and in the first statement are "internal" nodes, which we are arranging in all ways, whereas the n th Catalan number is counting full binary trees with n+1 leaf nodes . 正如在下面的意见建议由马克·迪金森,澄清:以上并在第一条语句图中提到的“节点”,“内部”节点,我们在各方面安排,而n个Catalan数的计数满具有n+1叶节点的二叉树 Binary trees with l leaf nodes have l - 1 internal nodes . 具有l叶节点的二叉树具有l - 1内部节点

  • This is basically wanting you to calculate number of unique BSTs' possible for a certain number of nodes. 这基本上是希望您为一定数量的节点计算唯一BST的数量。

  • In the end, final result will be multiplication of those numbers. 最后,最终结果将是这些数字的乘积。

  • If this was in an exam, then you will have to do the multiplication. 如果这是一次考试,那么您将必须进行乘法。 Otherwise, you can solve this programmatically using dynamic programming . 否则,您可以使用dynamic programming方式解决此问题。

CODE: 码:

class Solution {
        public int numTrees(int n) {
           if(n < 3) return n;
           int[] dp = new int[n+1];
           dp[0] = 1; // just initializing it as base case
           dp[1] = 1;// meaning, only 1 possibility for 1 node.
           dp[2] = 2;// meaning, only 2 possibilities for 2 nodes.

           for(int i=3;i<=n;++i){
               for(int j=1;j<=i;++j){
                   int nodes_on_left_of_j  = j - 1;
                   int nodes_on_right_of_j = i - j;
                   dp[i] += dp[nodes_on_left_of_j] * dp[nodes_on_right_of_j]; // so multiply left side possibilites with right side possibilites for a particular root node.
               }
           }

           return dp[n];
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM