Answered step by step
Verified Expert Solution
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 Mapmap= 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
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started