- I am trying to solve the graph datastructure problem of hacker rank.
- My method should return the minimal cost of providing libraries to all.
- Providing my hacker rank question here https://www.hackerrank.com/challenges/torque-and-development/problem?h_l=interview&playlist_slugs%5B%5D%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D%5B%5D=graphs&isFullScreen=true
- I am planning to use BFS and solve the problem.
- so I read some articles and found this link https://medium.com/basecs/breaking-down-breadth-first-search-cebe696709d9
- but the problem is I am getting this error TypeError: Cannot read property 'left' of undefined
- I used the medium code.
- providing my code snippet below.
- can you tell me how to fix it.
function roadsAndLibraries(n, c_lib, c_road, cities) {
console.log("roadsAndLibraries n--->", n);
console.log("roadsAndLibraries c_lib--->", c_lib);
console.log("roadsAndLibraries c_road--->", c_road);
console.log("roadsAndLibraries cities--->", cities);
var m = new Map();
m.set('a', 2);
m.set('b', 3);
m.set('b', 3);
m.set('b', 2);
m.set('b', 1);
console.log("map value--->", m);
// Check that a root node exists.
// if (rootNode === null) {
// return;
// }
// Check that a root node exists.
if (n === null) {
console.log("n root node--->", n);
return;
}
// Create our queue and push our root node into it.
// var queue = [];
// queue.push(rootNode);
// Create our queue and push our root node into it.
var queue = [];
queue.push(n);
console.log(" queue.push--->", queue);
while (queue.length > 0) {
// Create a reference to currentNode, at the top of the queue.
var currentNode = queue[0];
// If currentNode has a left child node, add it to the queue.
if (currentNode.left !== null) {
queue.push(currentNode.left)
}
// If currentNode has a right child node, add it to the queue.
if (currentNode.right !== null) {
queue.push(currentNode.right)
}
// Remove the currentNode from the queue.
queue.shift()
}
}
from TypeError: Cannot read property 'left' of undefined
No comments:
Post a Comment