Created
June 7, 2017 13:40
-
-
Save i-van/7146e27513c49102327bef629abb4b6a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function Node(cost) { | |
this.cost = cost; | |
this.children = []; | |
} | |
function getCheapestCost(rootNode) { | |
var n = rootNode.children.length; | |
// initialize minCost to the largest integer in the system | |
var minCost = Number.MAX_SAFE_INTEGER; | |
if (n === 0) { | |
return rootNode.cost; | |
} else { | |
for(let i = 0; i < n; ++i) { | |
let tempCost = getCheapestCost(rootNode.children[i]); | |
if (tempCost < minCost) | |
minCost = tempCost; | |
} | |
} | |
return minCost + rootNode.cost | |
} | |
var root = new Node(0); | |
console.log(getCheapestCost(root)); | |
root.children = [new Node(5), new Node(3), new Node(6)]; | |
root.children[0].children = [new Node(4)]; | |
root.children[1].children = [new Node(2), new Node(0)]; | |
root.children[2].children = [new Node(1), new Node(5)]; | |
root.children[1].children[0].children = [new Node(1)]; | |
console.log(getCheapestCost(root)); | |
root.children[1].children[1].children = [new Node(10)]; | |
console.log(getCheapestCost(root)); | |
root.children[1].children[0].children[0].children = [new Node(1)]; | |
console.log(getCheapestCost(root)); | |
root.children[1].children[0].children[0].children[0].children = [new Node(4)]; | |
console.log(getCheapestCost(root)); | |
root.children[2].children[0] = new Node(3); | |
console.log(getCheapestCost(root)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment