简体   繁体   中英

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 ? 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.

           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 . Binary trees with l leaf nodes have l - 1 internal nodes .

  • This is basically wanting you to calculate number of unique BSTs' possible for a certain number of nodes.

  • 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 .

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];
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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