Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

Please tell me how this recursive code works WITH DETAILS: import java.util.*; public class Main { // map to store all the paths (not necessarily

Please tell me how this recursive code works WITH DETAILS:

import java.util.*; public class Main { // map to store all the paths (not necessarily needed) . I added it so that we // can store all the paths and their cost. static Map map= new HashMap(); static String minPath = ""; static int minCost = Integer.MAX_VALUE; public static void main(String[] args) { int weight[] = {8, 7, 3, 4, 1, 5, 1, 5, 1}; int sum = minCostPath(weight, 0, 0,""); System.out.println("Minimum Cost Path "+ minPath + " cost = " + sum); } // recursive function to find the min cost path and min cost. public static int minCostPath(int []weight, int index, int cost, String path){ // base condition (i.e we reached the end of the tree) if(index >= weight.length){ path = path.substring(0,path.length()-2); if(!map.containsKey(path)){ map.put(path,cost); System.out.println(path + " cost = "+cost); } if(map.get(path) < minCost) { minCost = cost; minPath = path; } return cost; } cost += weight[index]; path += weight[index] + "->"; int leftSum = minCostPath(weight,index*2 +1, cost,path); int rightSum = minCostPath(weight, index*2 + 2, cost,path); return Math.min(leftSum, rightSum); } }

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Web Database Development Step By Step

Authors: Jim Buyens

1st Edition

0735609667, 978-0735609662

More Books

Students also viewed these Databases questions

Question

x-3+1, x23 Let f(x) = -*+3, * Answered: 1 week ago

Answered: 1 week ago