Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save jianminchen/860377327da61fe396ffb1a53682bcae to your computer and use it in GitHub Desktop.
Save jianminchen/860377327da61fe396ffb1a53682bcae to your computer and use it in GitHub Desktop.
practice to write cheapest cost of path in a tree, given a root node and each node's cost value as integer.
using System;
class Solution
{
class Node
{
public int value;
public Node[] children;
public Node parent;
}
static int getCheapestCost(Node rootNode)
{
// your code goes here
int minimalCost = int.MaxValue;
int existingValue = 0;
getCheapestCostRecursive(rootNode, existingValue, ref minimalCost);
return minimalCost;
}
private static void getCheapestCostRecursive(rootNode, int existingValue, ref minimalCost)
{
if(rootNode == null )
{
return;
}
// base case - rootNode - no children -
if(rootNode.Children == null )
{
var cost = existingValue;
minimalCost = (cost < minimalCost)? cost : minimalCost;
return ;
}
foreach(var child in rootNode.children)
{
int currentCost = child.Value;
int newValue = existingValue + currentCost;
getCheapestCostRecursive(child, newValue, ref minimalCost);
}
return; // reachable
}
static void Main(string[] args)
{
}
}
// recursive short to write, compared to iterative solution
// 5 paths
// save the path into a data structure IList<int>
// leaf node -> no children, ready to add IList<int>
// Go to IList<int> sum all the paths, find the minimum
// two variables - one is to track current path, all nodes on the path
// another variables - list all the path
// Dictionary< string, IList<int>
// public static void FindAllPaths(Node node, IList<int> path, IList<Ilist<int>> allPath)
// use recusrive easy to write - stack - using DFS
// leaf - easy to check
// make maxPathValue-> INt. int Value-> maxPathValue -> all Paths
// time - each at least once O(N), N - space stack -> logn ->
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment