We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
importjava.io.BufferedReader;importjava.io.FileReader;importjava.io.IOException;importjava.io.InputStreamReader;importjava.util.ArrayList;importjava.util.HashMap;importjava.util.List;importjava.util.Map;classResult{privatestaticfinalintMOD=1000000007;privatestaticfinalintMOD_10_8=(int)(Math.pow(10,8)+7);publicstaticvoidnumberBST(List<Integer>numbers){for(inti=0;i<numbers.size();i++){intnumNodesTmp=numbers.get(i);System.out.println(Result.totalNumberBTS(numNodesTmp));}}staticMap<Integer,Integer>memoization=newHashMap<Integer,Integer>();/** * The recursive function employing memoization estrategy. * * Lets define t(n) as total number of BST combinations for n nodes as next: * t(n) = sum(t(i-1)*t(n-i)) being 1<=i<=n and n=numberOfNodes * * The formula means that i is the root in turn of the BinarySearchTree (BST), and i has to take the value of each of the n nodes. * To the left of i there are t(i-1) BST combinations in which all nodes are less (equal) than i. * To the right of i there are t(n-i) BST combinations in which all nodes are greater (equal) than i. * * NOTE1: * the nodes have to be in order, but as we ony receive the number of nodes n and we iterate over them we do it in order. * * NOTE2: * the problem specifies to use modulo 10^8+7 instead of 10^9+7, its very possible its an error in the problem specification. * * @param numNodes * @return */publicstaticinttotalNumberBTS(intnumNodes){if(memoization.containsKey(numNodes)){returnmemoization.get(numNodes);}if(numNodes==0){return1;}if(numNodes==1){return1;}longcombinaciones=0;for(intj=1;j<=numNodes;j++){//combinaciones = (combinaciones + ((long)Result.totalNumberBTS(j-1)*Result.totalNumberBTS(numNodes-j))%(Result.MOD))%(Result.MOD);//We use 10^8+7 instead of 10^9+7, its very possible its an error in the problem specificationcombinaciones=(combinaciones+((long)Result.totalNumberBTS(j-1)*Result.totalNumberBTS(numNodes-j))%(Result.MOD_10_8))%(Result.MOD_10_8);}memoization.put(numNodes,(int)combinaciones);return(int)combinaciones;}}publicclassSolution{publicstaticvoidmain(String[]args)throwsIOException{//BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));BufferedReaderbufferedReader=newBufferedReader(newFileReader("in_bst.txt"));intnumbersCount=Integer.parseInt(bufferedReader.readLine().trim());List<Integer>numbers=newArrayList<>();for(inti=0;i<numbersCount;i++){intnumbersItem=Integer.parseInt(bufferedReader.readLine().trim());numbers.add(numbersItem);}Result.numberBST(numbers);bufferedReader.close();}}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Number of Binary Search Tree
You are viewing a single comment's thread. Return to all comments →
here is a java solution: