Amount of Time for Binary Tree to Be Infected - Parent Hashmap & BFS [JS]
- Get link
- X
- Other Apps
By
Anna An
on
Solution: Parent Hashmap & BFS
- DFS through the tree to record the parent node of each node in a hashmap and get the start node.
- Level-by-level BFS from the start node to get the total time to reach every node.
- Keep track of nodes we have visited to avoid revisiting.
- From every node, visit the parent, left child, and right child if they haven't been visited.
Time Complexity: O(n)
415ms
Space Complexity: O(n)
90.1MB
var amountOfTime = function(root, start) {
let parent = new Map(), startNode = null;
getParent(root);
let seen = new Set([startNode.val]), queue = [startNode], time = 0;
while (queue.length) {
for (let i = queue.length - 1; i >= 0; i--) {
let node = queue.shift();
if (parent.has(node.val)) {
let nodeParent = parent.get(node.val);
if (!seen.has(nodeParent.val)) {
queue.push(nodeParent);
seen.add(nodeParent.val);
}
}
if (node.left && !seen.has(node.left.val)) {
queue.push(node.left);
seen.add(node.left.val);
}
if (node.right && !seen.has(node.right.val)) {
queue.push(node.right);
seen.add(node.right.val);
}
}
time++;
}
return time - 1;
function getParent(node) {
if (node.val === start) startNode = node;
if (node.left) { // record the parent of the left child
parent.set(node.left.val, node);
getParent(node.left);
}
if (node.right) { // record the parent of the right child
parent.set(node.right.val, node);
getParent(node.right);
}
}
};
javascript
- Get link
- X
- Other Apps
Comments
Post a Comment