the question is taken from Pramp(really cool site!)
there is a more straight forward solution.
using recursion. but I thought trying it using BFS.
please review only the code of GetCheapestCost function and comment on space and time complexity
The car manufacturer Honda holds their distribution system in the form of a tree (not necessarily binary). The root is the company itself, and every node in the tree represents a car distributor that receives cars from the parent node and ships them to its children nodes. The leaf nodes are car dealerships that sell cars direct to consumers. In addition, every node holds an integer that is the cost of shipping a car to it.
Take for example the tree below:
0 / | \ 5 3 6 / / \ / \ 4 2 0 1 5 / / 1 10 \ 1
A path from Honda’s factory to a car dealership, which is a path from the root to a leaf in the tree, is called a Sales Path. The cost of a Sales Path is the sum of the costs for every node in the path. For example, in the tree above one Sales Path is 0→3→0→10, and its cost is 13 (0+3+0+10).
Honda wishes to find the minimal Sales Path cost in its distribution tree. Given a node rootNode, write a function getCheapestCost that calculates the minimal Sales Path cost in the tree.
Implement your function in the most efficient manner and analyze its time and space complexities.
For example:
Given the rootNode of the tree in diagram above
Your function would return:
7 since it’s the minimal Sales Path cost (there are actually two Sales Paths in the tree whose cost is 7: 0→6→1 and 0→3→2→1→1)
using System;
using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace TreeQuestions
{
/// <summary>
/// Sales Path
[TestClass]
public class PrampSalesPath
{
[TestMethod]
public void TestMethod1()
{
SalesNode rootNode = new SalesNode();
rootNode.children = new SalesNode[3];
rootNode.cost = 0;
rootNode.children[0] = new SalesNode {cost = 5};
rootNode.children[1] = new SalesNode {cost = 3};
rootNode.children[2] = new SalesNode {cost = 6};
Assert.AreEqual(3, PrampSalesPathelper.GetCheapestCost(rootNode));
}
}
public class SalesNode
{
public int cost;
public SalesNode[] children;
public SalesNode parent;
public SalesNode()
{
children = null;
parent = null;
}
}
public class PrampSalesPathelper
{
public static int GetCheapestCost(SalesNode rootNode)
{
//check root node is not null was not defined.
Queue<SalesNode> Q = new Queue<SalesNode>();
Q.Enqueue(rootNode);
int min = Int32.MaxValue;
while (Q.Count != 0)
{
var tempNode = Q.Dequeue();
//this is a leaf
if (tempNode.children == null)
{
min = Math.Min(min, tempNode.cost);
}
else
{
foreach (var node in tempNode.children)
{
node.cost += tempNode.cost;
Q.Enqueue(node);
}
}
}
return min;
}
}
}