java - printing optimal binary search tree in preorder dynamic programming algorith -
i have finished computing average cost of obst , know computed correctly. next task print tree in preorder. have attempt @ using recursion can't seem shake null pointer error.
here's code:
public class obst { static string[] keysa; static integer[][] root; public static void main(string[] args) { scanner sc = new scanner(system.in); int tot = sc.nextint(); hashmap<string, double> hm = new hashmap<string, double>(); int uniqnum = 0; string[] rawinput = new string[tot]; for(int i=0; i<tot; i++) { string tmp1 = sc.next(); if(i==0) { hm.put(tmp1, 1.0); uniqnum += 1.0; } else if( != 0) { if(!hm.containskey(tmp1)) { hm.put(tmp1, 1.0); uniqnum += 1.0; } else { double tmpfreq = 0.0; tmpfreq = hm.get(tmp1); hm.put(tmp1, (tmpfreq + 1.0)); } } } set<string> keys = hm.keyset(); keysa = keys.toarray(new string[uniqnum]); double[] freqsa = new double[uniqnum]; arrays.sort(keysa); for(int i=0; i<uniqnum; i++) { double tmp = 0.0; string tmpk = keysa[i]; tmp = hm.get(tmpk); tmp = tmp/tot; freqsa[i] = tmp; } double[][] eee = new double[uniqnum+2][uniqnum+1]; double[][] www = new double[uniqnum+2][uniqnum+1]; //matrix store optimal structure root = new integer[uniqnum+1][uniqnum+1]; for(int i=1; i<uniqnum+2; i++) { eee[i][i-1] = 0.0; www[i][i-1] = 0.0; } for(int l=1; l<uniqnum+1; l++) { for(int i=1; i<=uniqnum-l+1; i++) { int j = + l - 1; eee[i][j] = double.max_value; www[i][j] = www[i][j-1] + freqsa[j-1]; for(int r=i; r<=j; r++) { double t = eee[i][r-1] + eee[r+1][j] + www[i][j]; if(t<eee[i][j]) { eee[i][j] = t; root[i][j] = r-1; } } } } //total cost system.out.println(eee[1][uniqnum]); printtree(1,uniqnum-1,-1, ""); } public static void printtree(int min, int max, int parent, string s) { int r = root[min][max]; if(parent == -1 ) { system.out.println(keysa[r] + " root"); } else if(min < parent) { system.out.println(keysa[r] + " left child of " + s); } else { system.out.println(keysa[r] + " right child of " + s); } if(min < max) { printtree(min,r,r+1,keysa[r]); printtree(r+1,max,r,keysa[r]); } } } my trouble in method print tree.
looks aren't checking bounds correctly. if there no left or right child, shouldn't printing side. make sure check r+1 within array size, , node exists there. same both left , right sides.
Comments
Post a Comment