BST optimal binary search tree (Java version)

Source: Internet
Author: User

The content was last summer, but it never came true.

In fact, it is the interval DP, to find a sequence to form a binary tree, the sequence of sequential traversal.

The core is the same as the rest of the interval DP, which enumerates the intermediate values. Then the probability of the whole interval is summed up after enumeration, because it is equivalent to a deeper layer.

Java code, test data attached

Import Java.util.arrays;import Java.util.scanner;public class Main {/** * input P: Access probability array; 0,1,.... n is a well-ordered key value * Output A=new float[ N][n]: Optimal time Matrix * output R=new int[n][n]: root node Matrix * @param p * @param A * @param R */static void Optimalbst (double[] p, double[][] A, int[][] R) {int n = p.length; Arrays.sort (P); for (int i = 0; i < n; i++) {a[i][i] = P[i]; R[i][i] = i;  The root is itself}for (int len = 1, len < n; len++) {for (int st = 0; St + len < n; st++) {int ed = st + Len;int  root = st;double min = double.max_value;for (int k = st; k <= ed; k++) {double tmp;if (k = = st) tmp = a[k + 1][ed];else if (k = = ed) tmp = A[st][k-1];elsetmp = A[k + 1][ed] + a[st][k-1];if (min > tmp) {min = Tmp;root = k;}} R[st][ed] = root; A[st][ed] = min;for (int i = st; I <= ed; i++) a[st][ed] + = P[i];}}} public static void print (int st,int ed,int [] R) {if (st==ed) {System.out.print (r[st][ed]); return;} System.out.print ("(");p rint (st,r[st][ed]-1,r); System.out.print (")"); System.out.print (r[st][ed]); System.out.prInt ("(");p rint (r[st][ed]+1,ed,r); System.out.print (")");}  public static void Main (string[] args) {//scanner input = new Scanner (system.in);d ouble [] A = new Double[5][5];int [] R = new Int[5][5];//optimalbst1 (new double [] {0.15, 0.10,0.05,0.10,0.20},a,r);//system.out.println (A[0][4]);//print ( 0,4,R); Optimalbst (new double [] {0.15, 0.10,0.05,0.10,0.20},a,r); System.out.println (a[0][4]);p rint (0,4,r);}}


BST optimal binary search tree (Java version)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.